如何将具有相似元素的元组序列分组以保持顺序?

时间:2012-07-06 18:59:06

标签: python sequence

我需要一个接受两个元素元组列表的函数,并返回这些元组,这些元组在列表中分组,其中元组的第二个元素相等,并保留原始序列顺序。例如,

>>> seq = [(0, 1), (1, 2), (2, 2), (3, 2), (4, 1), (5, 3), (6, 3), (7, 2)]
>>> split_repeated(seq)
[[(0, 1)], [(1, 2), (2, 2), (3, 2)], [(4, 1)], [(5, 3), (6, 3)], [(7, 2)]]

如果我平坦结果,我必须得到原始序列:

>>> itertools.chain.from_iterable(split_repeated(seq)) == seq
True

1 个答案:

答案 0 :(得分:2)

>>> seq = [(0, 1), (1, 2), (2, 2), (3, 2), (4, 1), (5, 3), (6, 3), (7, 2)]
>>> from itertools import groupby
>>> from operator import itemgetter
>>> [list(items) for key,items in groupby(seq,key=itemgetter(1))]
[[(0, 1)], [(1, 2), (2, 2), (3, 2)], [(4, 1)], [(5, 3), (6, 3)], [(7, 2)]]