Skip to content Skip to sidebar Skip to footer

Using Itertools To Group Consecutive Tuples By Second Value

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 gr

Solution 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.


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

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

Post a Comment for "Using Itertools To Group Consecutive Tuples By Second Value"