Вопрос

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?

Это было полезно?

Решение

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)
>>>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top