Python`for`不会迭代枚举对象 [英] Python `for` does not iterate over enumerate object

查看:133
本文介绍了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()函数中使用它并因此耗尽它。因此,以下尝试在中使用循环不会产生任何效果。

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)]上引发IndexError。附加(v);我不会为你解决这个问题,但这足以表明循环体开始执行了。

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.

这篇关于Python`for`不会迭代枚举对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆