我正在尝试按列表中的第一个元素组合列表/元组列表 - 如下所示:
输入:
[(1, [32, 432, 54]), (1, [43, 54, 65]), (2, [2, 43, 54]), (2, [1, 5, 6])]
输出:
[(1, [32, 432, 54], [43, 54, 65]), (2, [2, 43, 54], [1, 5, 6])]
列表实际上是按照我的示例输入中的第一个元素排序的,如果最后元组是列表则无关紧要。
有效/ pythonic方式吗?
答案 0 :(得分:4)
使用itertools.groupby
和list 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])]