我有一个多维数据列表示例:
example_list=[
["a","b","c", 2,4,5,7],
["e","f","g",0,0,1,5],
["e","f","g", 1,4,5,7],
["a","b","c", 3,2,5,7]
]
如何将它们放在这样的组中:
out_list=[
[["a","b","c", 2,4,5,7],
["a","b","c",3,2,5,7]
],
[["e","f","g", 0,0,1,5],
["e","f","g", 1,4,5,7]
]
]
我试过这个:
example_list=[["a","b","c", 2,4,5,7],["e","f","g", 0,0,1,5],["e","f","g",1,4,5,7],["a","b","c", 3,2,5,7]]
unique=[]
index=0
for i in range(len(example_list)):
newlist=[]
if example_list[i][:3]==example_list[index][:3]:
newlist.append(example_list[i])
index=index+1
unique.append(newlist)
print unique
我的结果是:
[[['a','b','c',2,4,5,7],[['e','f','g',0,0,1,5] ],[['e','f','g',1,4,5,7],[['a','b','c',3,2,5,7]]]
我无法理解。 请帮忙。 谢谢, Shiuli
答案 0 :(得分:0)
如果分组由每个列表中的前三个元素决定,则代码将执行您要求的内容:
from collections import defaultdict
example_list=[["a","b","c", 2,4,5,7],["e","f","g",0,0,1,5],["e","f","g", 1,4,5,7],["a","b","c", 3,2,5,7]]
d = defaultdict(list)
for l in example_list:
d[tuple(l[:3])].append(l)
print d.values() # [[['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7]], ...]
这将使用defaultdict
生成一个字典,其中键是前三个元素,值是以这些元素开头的列表列表。
答案 1 :(得分:0)
首先使用sorted()
对列表进行排序,并提供lambda
函数作为键。
>>> a = sorted(example_list, key=lambda x:x[:3])
[['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7], ['e', 'f', 'g', 0, 0, 1, 5], ['e', 'f', 'g', 1, 4, 5, 7]]
然后在排序列表中使用itertools.groupby()
:
>>> [list(v) for k, v in groupby(a, lambda x:x[:3])]
[
[['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7]],
[['e', 'f', 'g', 0, 0, 1, 5], ['e', 'f', 'g', 1, 4, 5, 7]]
]