user3378649
user3378649

Reputation: 5354

grouping list of tuples with itertools

I am trying to group data based on second argument.

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

I am excuting code from this thread

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

But instead of getting a result that look like: [[(1,1),(3,1),(2,1)],[(5,0),(3,0)]]

Why I am getting the last tuple in a seperated list, while I should get it grouped with other values where 1 is a second values

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

Upvotes: 0

Views: 323

Answers (1)

inspectorG4dget
inspectorG4dget

Reputation: 113905

This has tripped me up in the past as well. If you want it to group globally, it's best to sort the list first:

In [163]: test = [(1,1),(3,1),(5,0),(3,0),(2,1)]

In [164]: crit = operator.itemgetter(1)

In [165]: test.sort(key=crit)

In [166]: result = [list(group) for key, group in itertools.groupby(test, crit)]

In [167]: result
Out[167]: [[(5, 0), (3, 0)], [(1, 1), (3, 1), (2, 1)]]

Upvotes: 1

Related Questions