To illustrate, I start with a list of 2 tuples:
import itertools import operator raw = [(1, "one"), (2, "two"), (1, "one"), (3, "three"), (2, "two")] for key, grp in itertools.groupby(raw, key=lambda item: item[0]): print key, list(grp).pop()[1]
gives:
1 one 2 two 1 one 3 three 2 two
In an attempt to find out why:
for key, grp in itertools.groupby(raw, key=lambda item: item[0]): print key, list(grp)
Even this will give me the same result:
for key, grp in itertools.groupby(raw, key=operator.itemgetter(0)): print key, list(grp)
I want to get something like:
1 one, one 2 two, two 3 three
I think this is because the key is inside the tuple inside the list, when in fact the tuple moves as one. Is there a way to achieve the desired result? Maybe groupby() not suitable for this task?
python group-by itertools
Kit
source share