提问人:knightcool 提问时间:11/17/2023 更新时间:11/17/2023 访问量:37
Python 生成器在迭代期间缺少值
Python generator missing a value during iteration
问:
您好,在我的代码中使用生成器时,我注意到这种奇怪的行为,即在脱离循环后,对生成器的调用会跳过一个值。示例代码:next()
from itertools import cycle
def endless():
yield from cycle((9,8,7,6))
total=0
e = endless()
for i in e:
if total<30:
total += i
print(i, end=" ")
else:
print()
print("Reached the goal!")
break
print(next(e), next(e), next(e))
这将输出:
9 8 7 6
Reached the goal!
8 7 6
为什么脱离循环后跳过打印。我希望它会打印以下内容:9
9 8 7 6
Reached the goal!
9 8 7
答:
1赞
Tom Karzes
11/17/2023
#1
缺少的是最后一次循环迭代的值。在该迭代中,是 ,但循环退出而不打印它。下一个值是 。9
i
i
9
8
您可以通过始终在循环中打印当前值来修复它:
#!/usr/bin/python3
from itertools import cycle
def endless():
yield from cycle((9,8,7,6))
total=0
e = endless()
for i in e:
total += i
print(i, end=" ")
if total >= 30:
print()
print("Reached the goal!")
break
print(next(e), next(e), next(e))
这会产生:
9 8 7 6
Reached the goal!
9 8 7
评论
6
24
else
total += 1
if