我一直试图转换一些数据,每组中的第一个值是组标识符:
data = [(a, 1, 2), (a, 3, 4), (b, 5, 6)]
到
data = [[(1, 2), (3, 4)], [(5, 6)]]
最简单的方法是什么?提前致谢
答案 0 :(得分:5)
如果data
列表按分组键排序,您可以使用itertools.groupby
:
In [1]: from itertools import groupby
In [2]: from operator import itemgetter
In [3]: data = [(a, 1, 2), (a, 3, 4), (b, 5, 6)]
In [4]: [[l[1:] for l in group] for _, group in groupby(data, key=itemgetter(0))]
Out[4]: [[(1, 2), (3, 4)], [(5, 6)]]