[英]How to get index of key/group in itertools.groupby?
When using the groupby
function from itertools
, is there a nice way to get the index of the key/group
tuple? 当使用
itertools
的groupby
函数时,是否有一种很好的方法来获取key/group
元组的索引? 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: 您需要在括号中放置
key
和group
:
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.