如何通过使它们的第一个元素相同来定义分组,并将它们保留在列表列表中?

时间:2018-07-26 17:03:03

标签: python list

我有一个列表

list1 = [(4356, 'OPIL', 2), (4356, 'OILY', 3), (5986, 'UISL', 1), (6985, 'LIBK', 3), (6985, 'LIBK', 1)]

我希望输出如下所示: 输出:

result = [[(4356, 'OPIL', 2),(4356, 'OILY', 3)],[(5986, 'UISL', 1)], [(6985, 'LIBK', 3), (6985, 'LIBK', 1)]]

我们如何做到?

2 个答案:

答案 0 :(得分:2)

使用groupby中的itertools

from itertools import groupby

list1 = [(4356, 'OPIL', 2), (4356, 'OILY', 3), (5986, 'UISL', 1), (6985, 'LIBK', 3), (6985, 'LIBK', 1)]

l = [list(v) for g, v in groupby(list1, key=lambda v: v[0])]
print(l)

输出:

[[(4356, 'OPIL', 2), (4356, 'OILY', 3)], [(5986, 'UISL', 1)], [(6985, 'LIBK', 3), (6985, 'LIBK', 1)]]

答案 1 :(得分:0)

假设列表中的项已排序,则可以使用itertools.groupby()

In [1]: list1 = [(4356, 'OPIL', 2), (4356, 'OILY', 3), (5986, 'UISL', 1), (6985, 'LIBK', 3), (6985, 'LIBK', 1)]

In [2]: from itertools import groupby

In [3]: from operator import itemgetter

In [4]: [list(g) for _, g in groupby(list1, key=itemgetter(0))]
Out[4]: 
[[(4356, 'OPIL', 2), (4356, 'OILY', 3)],
 [(5986, 'UISL', 1)],
 [(6985, 'LIBK', 3), (6985, 'LIBK', 1)]]

如果未排序,则可以使用groupby()预先对列表进行排序,也可以使用其他策略-例如,使用collections.defaultdict()将“相似”的项目分组:

In [5]: from collections import defaultdict

In [6]: grouped = defaultdict(list)

In [7]: for item in list1:
            grouped[item[0]].append(item)   

In [8]: [grouped[key] for key in sorted(grouped)] 
Out[8]: 
[[(4356, 'OPIL', 2), (4356, 'OILY', 3)],
 [(5986, 'UISL', 1)],
 [(6985, 'LIBK', 3), (6985, 'LIBK', 1)]]