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

问题描述

为什么不迭代?

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 )

输出:

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

文档:

  • https://docs.python.org/3/reference/compound_stmts.html#for
  • https://docs.python.org/3/library/functions.html#enumerate

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


解决方案

任何迭代器在某种意义上都是一次性的",当它完全执行时,它会变成空的,不能再使用了.当你调用 logging.debug(list(e)) 时,你已经在 list() 函数中使用了它,所以用尽了它.因此,以下在 for 循环中使用它的尝试没有给出任何结果.

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.

在此调试后再次调用 enumerate() 时,使用修改后的代码,脚本行为会发生变化 - 它会在 y[int(k)].append( v ) 上引发 IndexError;我不会为你解决这个问题,但这足以表明循环体开始执行.

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.

相关文章