Python `for` does not iterate over enumerate object

一世执手 提交于 2019-12-02 11:56:19

Any iterator is "one-shot" in sense that, when it is fully executed, it becomes empty and can't be used anymore. When you called logging.debug( list(e) ), you have used it in the list() function and so exhausted it. So, the following attempt to use it in for cycle gives nothing.

With modified code when enumerate() is called again after this debug, the script behavior gets changed - it raises IndexError on y[int(k)].append( v ); I won't fix this for you but this is enough sign that cycle body begins being executed.

Because enumerate returns an iterator:

>>> e = enumerate(range(4))
>>> list(e)
[(0, 0), (1, 1), (2, 2), (3, 3)]
>>> list(e)
[]

Once the end is reached, e.next() raises a StopIteration exception:

>>> e.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Thus you cannot iterate twice over e. You will have to recreate the iterator.

this line :

logging.debug( list(e) )

consumes the iterator, so when you get here:

for k, v in e:
   # ...

e is already exhausted.

try this instead:

e = list(enumerate(d))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!