简体   繁体   English

Python:按第一个元素连接列表列表

[英]Python: Join lists of lists by the first element

I'm trying to combine a list of lists/tuples by the first element in the list - something like this: 我正在尝试通过列表中的第一个元素组合列表/元组列表-像这样:

Input: 输入:

[(1, [32, 432, 54]), (1, [43, 54, 65]), (2, [2, 43, 54]), (2, [1, 5, 6])]

Output: 输出:

[(1, [32, 432, 54], [43, 54, 65]), (2, [2, 43, 54], [1, 5, 6])]

The lists are actually ordered by the first element like in my example input, and it doesn't matter if at the end the tuples are lists. 列表实际上是按第一个元素排序的,就像在我的示例输入中一样,并且最后元组是否是列表也没有关系。

Is there an efficient/pythonic way to do this? 有没有一种有效的/ python方式来做到这一点?

Using itertools.groupby and list comprehension : 使用itertools.groupbylist comprehension

>>> lst = [(1, [32, 432, 54]), (1, [43, 54, 65]), (2, [2, 43, 54]), (2, [1, 5, 6])]
>>> import itertools
>>> [(key,) + tuple(v for k, v in grp)
...     for key, grp in itertools.groupby(lst, key=lambda x: x[0])]
[(1, [32, 432, 54], [43, 54, 65]), (2, [2, 43, 54], [1, 5, 6])]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM