【发布时间】:2021-11-04 20:43:48
【问题描述】:
在下面的代码 sn-p 中,您将如何使用运算符 += 而不是键入四次 print(next(seq)) 来增加 next() 调用?在while 循环中,只有print(next(seq)) 的第一个实例会重复打印。每次迭代如何推进到下一个?
def get_sequence_upto(x):
for i in range(x):
yield i
seq = get_sequence_upto(5)
print(next(seq))
print(next(seq))
print(next(seq))
print(next(seq))
输出:
0
1
2
3
编辑:添加了while循环sn-p
while True:
seq = loop_here(x)
print(next(seq))
我尝试将 += 添加到代码中的不同点,但没有成功。
【问题讨论】:
-
With this in a while loop, only the first instance of print(next(seq)) will print repeatedly不,这不会发生,因为您没有将seq = get_sequence_upto(5)放入 while 循环中。 -
对不起,while循环的代码有点不同,但概念是一样的。
-
请提供代码
-
我添加了 while 循环部分 - 谢谢
-
请将
seq = loop_here(x)保留在while 循环之外,您将在循环的每次迭代中重新初始化seq。另外最好使用For ... in,否则你必须用try ... except处理StopIteration异常
标签: python python-3.x while-loop generator yield