我想从列表列表中生成不同的列表。参见示例
[['this', "isn't", 'working'], ['working', 'great'], ["isn't", 'working'], ['and'], ['great'], ['working', 'this', "isn't"]]
应该像
list1 = [['and'], ['great']]
list2 = [['working', 'great'], ["isn't", 'working']]
list3 = [['this', "isn't", 'working'],['working', 'this', "isn't"]]
like wise...list4 having 4 elements and so on.
,然后将它们转换为数据帧。但是目前,我想基于这些元素创建列表。如果可以提出一些想法,将会有所帮助。出于示例目的,在示例中显示了一个小列表,这将是一个大列表,因此可以理解一种有效的技术。
谢谢。
答案 0 :(得分:5)
一种方法是定义一个defaultdict
,并插入具有与子列表的长度相对应的键的元素,并通过键保留dict.values
sorted
:
from collections import defaultdict
d = defaultdict(list)
for subl in l:
d[len(subl)].append(subl)
out = [d[i] for i in sorted(d)]
print(out)
[[['and'], ['great']],
[['working', 'great'], ["isn't", 'working']],
[['this', "isn't", 'working'], ['working', 'this', "isn't"]]]