Question

When using the groupby function from itertools, is there a nice way to get the index of the key/group tuple? I would like to avoid to have to do :

index = 0
for key, group in itertools.groupby(myList, myFunc) :
  ...
  index += 1

Is it possible to do something with enumerate for example?

Was it helpful?

Solution

You need to place key and group in parenthesis:

for index, (key, group) in enumerate(itertools.groupby(myList, myFunc)):

Below is a demonstration:

>>> # lst represents what is returned by itertools.groupby
>>> lst = [(1, 2), (3, 4), (5, 6)]
>>> for i, (j, k) in enumerate(lst):
...     i, j, k
...
(0, 1, 2)
(1, 3, 4)
(2, 5, 6)
>>>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top