您的位置:首页技术文章
文章详情页

python - 用生成器迭代数据在文件和IDLE中运行结果不一致,

浏览:83日期:2022-06-30 18:38:38

问题描述

使用生成器迭代数据构造丢失问题,同样的代码运行结果不一致:

文件方式运行得到结果为:5 2 1 0

Python自带IDLE运行得到结果为:5 3 2 1 0

def countdown(n): while n >= 0:newvalue = (yield n)if newvalue is not None: n = newvalueelse: n -= 1c = countdown(5)for n in c: print(n) if n == 5:c.send(3)

python - 用生成器迭代数据在文件和IDLE中运行结果不一致,

问题解答

回答1:

不要对正在遍历的对象进行修改, 那样会导致索引混乱, 无法达到我们想要的结果, 可以通过enumerate查看遍历过程中, 索引的变化

for index, n in enumerate(c): # index 为取到的索引值 print(index, n) if n == 5:c.send(3)

标签: Python 编程
相关文章: