![](/img/trans.png)
[英]Get all first element of tuples from list of lists of tuples in Python
[英]How to recategorize a list of tuples by the first element in Python?
使用 Python3.x,我有一个元组列表如下(其中第一个元素是整数或字符串):
tuple_list = [(1, 'AA', 515), (1, 'BBT', 101),
(1, 'CZF', 20), (2, 'TYZ', 8341), (2, 'ONR', 11)]
在此示例中,一些元组以1
开头,其他元组以2
开头。 每个都被放入一个单独的列表中。
我想要一种方法将具有相同第一个元素的元组“分类”到单独的列表中。
在这种情况下,所需的解决方案如下,一个列表列表:
[[(1, 'AA', 515), (1, 'BBT', 101), (1, 'CZF', 20)],
[(2, 'TYZ', 8341), (2, 'ONR', 11)]]
这可以通过迭代和检查每个(唯一的)第一个元素的列表是否存在来实现,但是对于具有更多“唯一”第一个元素而不是简单的1
和2
更大列表,这在计算上会很昂贵。
如何做到这一点才能快速/高效?
使用itertools.groupby
。 与operator.itemgetter
配对以实现高效查找/切片。
from itertools import groupby
from operator import itemgetter
tuple_list = [(1, 'AA', 515), (1, 'BBT', 101), (1, 'CZF', 20), (2, 'TYZ', 8341), (2, 'ONR', 11)]
get_first = itemgetter(0)
result = [list(g) for k, g in groupby(sorted(tuple_list, key=get_first), get_first)]
结果:
[[(1, 'AA', 515), (1, 'BBT', 101), (1, 'CZF', 20)], [(2, 'TYZ', 8341), (2, 'ONR', 11)]]
from collections import defaultdict
d = defaultdict(list)
for t in tuple_list:
d[t[0]].append(t)
result = list(d.values())
结果:
[[(1, 'AA', 515), (1, 'BBT', 101), (1, 'CZF', 20)], [(2, 'TYZ', 8341), (2, 'ONR', 11)]]
一种方法是使用defaultdict
并将第一个元素存储为索引,然后将它们分组,如下所示:
from collections import defaultdict
tuple_list = [(1, 'AA', 515), (1, 'BBT', 101),
(1, 'CZF', 20), (2, 'TYZ', 8341), (2, 'ONR', 11)]
dct = defaultdict(list)
for l in tuple_list:
dct[l[0]].append(l)
print(sorted(dct.values(), key=lambda l: l[0][0]))
>>> [[(1, 'AA', 515), (1, 'BBT', 101), (1, 'CZF', 20)], [(2, 'TYZ', 8341), (2, 'ONR', 11)]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.