您好,在我的代码中使用生成器时,我注意到这种奇怪的行为,在脱离循环后,对生成器的
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
缺失的
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