Python_grouping 多维列表

Python_grouping multidimensional list

我有一个多维列表示例:

    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]], ...]

这将使用 defaultdict 生成字典,其中键是前三个元素,值是以这些元素开头的列表列表。

首先简单地使用 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]]
]