![](/img/trans.png)
[英]How to compare N lists in python and create a new list with unique elements
[英]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.