Python `for` does not iterate over enumerate object(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.
这篇关于Python `for` 不会遍历枚举对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python `for` 不会遍历枚举对象


基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01