繁体   English   中英

Python:按长度比较列表的列表并创建大小相等的新列表

[英]Python : compare lists of a list by length and create new lists of equal sizes

我有一个大列表,其中包含多个任意长度的列表。 我想比较每个列表的长度并创建相等大小的新列表。 例如,

biglist = [['x','y','z'],['a','b'],['d','f','g'],...,['r','e','w','q','t','u','i']]
expected_list= [['a','b'],[['x','y','z'],['d','f','g']],....,['r','e','w','q','t','u','i']] 

我是python的新手。 有人可以建议我用一种较便宜的方法来完成上述过程吗? 提前致谢。

看起来您想按其元素len s对列表进行groupby

>>> biglist = [['x', 'y', 'z'], ['a', 'b'], ['d', 'f', 'g'], ['r', 'e', 'w', 'q', 't', 'u', 'i']]
>>> expected_list = [list(b) for a, b in itertools.groupby(sorted(biglist, key=len), len)]
>>> expected_list
[[['a', 'b']], [['x', 'y', 'z'], ['d', 'f', 'g']], [['r', 'e', 'w', 'q', 't', 'u', 'i']]]

我可以建议使用itertools groupby函数吗?

import itertools


biglist = [['x','y','z'],['a','b'],['d','f','g'],['r','e','w','q','t','u','i']]

print(list(list(i[1]) for i in itertools.groupby(sorted(biglist, key=len), len)))

哪个输出

[[['a', 'b']], [['x', 'y', 'z'], ['d', 'f', 'g']], [['r', 'e', 'w', 'q', 't', 'u', 'i']]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM