简体   繁体   English

Python `for` 不会遍历枚举对象

[英]Python `for` does not iterate over enumerate object

Why does this not iterate?为什么这不迭代?

import logging
logging.basicConfig(level=logging.DEBUG)

x = []
y = [[] for n in range(0, 1)]
linedata = ["0","1","2"]
x.append( linedata[0] )

d = linedata[1:] 
logging.debug( "d: {}".format(d) )
e = enumerate(d)
logging.debug( list(e) )
for k, v in e:
  logging.debug( "k:{} v:{}".format( k, v ) )
  y[int(k)].append( v )
  #for d in [(0,1)]:
  #logging.debug( "k:{} v:{}".format( d[0], d[1] ) )
  #y[d[0]].append( d[1] )

logging.debug( x )
logging.debug( y )

Output:输出:

DEBUG:root:d: ['1', '2']
DEBUG:root:[(0, '1'), (1, '2')]
DEBUG:root:['0']
DEBUG:root:[[]]

Docs:文档:

Run online: http://goo.gl/75yuAd在线运行: http : //goo.gl/75yuAd

Because enumerate returns an iterator:因为enumerate返回一个迭代器:

>>> 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()会引发一个StopIteration异常:

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

Thus you cannot iterate twice over e .因此,您不能在e迭代两次。 You will have to recreate the iterator.您将不得不重新创建迭代器。

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.当您调用logging.debug( list(e) ) ,您已经在 list() 函数中使用了它,因此耗尽了它。 So, the following attempt to use it in for cycle gives nothing.因此,以下尝试在for循环中使用它没有任何结果。

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 ) ;在此调试后再次调用 enumerate() 时修改代码,脚本行为发生变化 - 它在y[int(k)].append( v )上引发 IndexError ; I won't fix this for you but this is enough sign that cycle body begins being executed.我不会为你解决这个问题,但这足以表明循环体开始执行。

this line :这一行:

logging.debug( list(e) )

consumes the iterator, so when you get here:消耗迭代器,所以当你到达这里时:

for k, v in e:
   # ...

e is already exhausted. e已经用完了。

试试这个:

e = list(enumerate(d))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM