Python\u分组多维列表
我有一个多维列表示例:Python\u分组多维列表,python,multidimensional-array,python-2.5,Python,Multidimensional Array,Python 2.5,我有一个多维列表示例: 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
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]]
我无法理解。如果分组由每个列表中的前三个元素决定,则以下代码将满足您的要求:
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]], ...]
这将用于生成一个字典,其中键是前三个元素,值是以这些元素开头的列表列表。首先使用
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]]
然后在已排序的列表上使用:
>>> [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]]
]
分组是否取决于前三个元素?