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` 不会遍历枚举对象
基础教程推荐
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 包装空间模型 2022-01-01
