Python 生成器和 yield - 递增到 while 循环中的 next() 调用
Python generators and yield - increment to the next() call in a while loop
在下面的代码片段中,您如何使用运算符 +=
来递增 next()
调用,而不是键入四次 print(next(seq))
?在 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 循环片段
while True:
seq = loop_here(x)
print(next(seq))
我曾尝试将 += 添加到代码中的不同点,但没有成功。
您可以像下面这样使用 for 循环:
def get_sequence_upto(x):
for i in range(x):
yield i
seq = get_sequence_upto(5)
while seq:
try:
print(next(seq))
except:
break
将 yield from
与 for 循环一起使用:
def get_sequence_upto(x):
yield from range(x)
nums = get_sequence_upto(5)
while True:
x = next(nums, None)
if x is not None:
print(x)
continue
break
或 try
except
:
def get_sequence_upto(x):
yield from range(x)
nums = get_sequence_upto(5)
while True:
try:
print(next(nums))
except StopIteration:
break
在下面的代码片段中,您如何使用运算符 +=
来递增 next()
调用,而不是键入四次 print(next(seq))
?在 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 循环片段
while True:
seq = loop_here(x)
print(next(seq))
我曾尝试将 += 添加到代码中的不同点,但没有成功。
您可以像下面这样使用 for 循环:
def get_sequence_upto(x):
for i in range(x):
yield i
seq = get_sequence_upto(5)
while seq:
try:
print(next(seq))
except:
break
将 yield from
与 for 循环一起使用:
def get_sequence_upto(x):
yield from range(x)
nums = get_sequence_upto(5)
while True:
x = next(nums, None)
if x is not None:
print(x)
continue
break
或 try
except
:
def get_sequence_upto(x):
yield from range(x)
nums = get_sequence_upto(5)
while True:
try:
print(next(nums))
except StopIteration:
break