[英]Python : compare lists of a list by length and create new lists of equal sizes
i have a big list that consists of multiple lists of arbitrary lengths. 我有一个大列表,其中包含多个任意长度的列表。 I want to compare each list length and create new lists of equal sizes.
我想比较每个列表的长度并创建相等大小的新列表。 For example,
例如,
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']]
I am new to python. 我是python的新手。 can anyone suggest me a less expensive method to do the above process.
有人可以建议我用一种较便宜的方法来完成上述过程吗? Thanks in advance.
提前致谢。
It looks like you want to groupby
a list by its element len
s: 看起来您想按其元素
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']]]
May I suggest using itertools groupby function? 我可以建议使用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)))
Which outputs 哪个输出
[[['a', 'b']], [['x', 'y', 'z'], ['d', 'f', 'g']], [['r', 'e', 'w', 'q', 't', 'u', 'i']]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.