문제

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