使用itertools按第二个值对连续元组进行分组

时间:2014-03-16 23:51:13

标签: python tuples itertools

我有一组表格中的数据:

X1 = [(1,1),(3,1),(5,0),(3,0),(2,1)]

我无法弄清楚如何将它们分组:

X2 = [[(1,1),(3,1)],[(5,0),(3,0)],[(2,1)]]

即。它们按照每个元组中的第二个值以连续方式分组。

我知道这是有道理的:

http://docs.python.org/2/library/itertools.html#itertools.groupby

3 个答案:

答案 0 :(得分:5)

from itertools import groupby
from operator import itemgetter
X2 = [list(group) for key, group in groupby(X1, itemgetter(1))]

key函数传递给groupby,获取每个元组的第二项,以便groupby将元组按第二项分组。

答案 1 :(得分:0)

from itertools import groupby, imap
from operator  import itemgetter

X1 = [(1,1),(3,1),(5,0),(3,0),(2,1)]
print map(list, imap(itemgetter(1), groupby(X1, itemgetter(1))))
# -> [[(1, 1), (3, 1)], [(5, 0), (3, 0)], [(2, 1)]]

答案 2 :(得分:-2)

x = [(1,1),(3,1),(5,0),(3,0),(2,1)]
y = [x[n:n+2] for n in range(0, len(x), 2)]
print(y)