Using itertools to group consecutive tuples by second value

*爱你&永不变心* 提交于 2019-12-12 17:36:01

问题


I have a set of data in the form:

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

I can't figure out how to group them such that:

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

i.e. they are grouped in a consecutive fashion by the second value in each tuple.

I know it's something with this:

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


回答1:


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

Pass a key function to groupby that fetches the second item of each tuple, so groupby groups the tuples by their second items.




回答2:


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)]]



回答3:


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)


来源:https://stackoverflow.com/questions/22444728/using-itertools-to-group-consecutive-tuples-by-second-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!