【发布时间】:2020-01-28 00:39:42
【问题描述】:
我正在尝试使用生成器生成奇数列表(只是为了更好地了解生成器)。我编写了以下代码,但是它并没有停止运行!虽然我希望当条件 i>n 满足时代码会停止。 任何帮助表示赞赏。
import sys
def odd(n):
i=0
while True:
if i%2==0:
continue
yield i
i+=1
if i>n:
return
# Here we build a generator
g = odd(10)
while True:
try:
print(next(g),end=' ')
except StopIteration:
sys.exit()
【问题讨论】:
-
当
i是偶数时,你永远不会增加它。它甚至永远存在。 -
你不是在提出停止迭代,你只是在回归。
-
@Neil 这基本上就是
return在生成器函数中所做的。 -
@chepner 在 StopIteration 上使用 while 循环和 try/except 仍然很奇怪,而不是
for -
@CorentinLimier 不过,这与问题没有任何关系。