问题描述
为什么不迭代?
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.
这篇关于Python `for` 不会遍历枚举对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)