Python 生成器在迭代期间缺少值

问题描述 投票:0回答:1

您好,在我的代码中使用生成器时,我注意到这种奇怪的行为,在脱离循环后,对生成器的

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
python loops for-loop iterator generator
1个回答
0
投票

缺失的

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
© www.soinside.com 2019 - 2024. All rights reserved.