在python中,生成器可以返回一个最终值,该值被传递给StopIteration
异常:
def gen():
yield 3
yield 1
return 2
> g = gen()
> next(g)
3
> next(g)
1
> next(g)
Traceback (most recent call last): ...
next(g)
StopIteration: 2
> next(g)
Traceback (most recent call last): ...
next(g)
StopIteration
是否有任何方法可以访问在for循环中引发的StopIteration传递的值?比如:
> result = 0
> for x in gen():
result += x
else catch StopIteration as y:
result /= y.args[0]
> result
2
不;for
循环吞下StopIteration
异常。如果您关心StopIteration
异常的细节,则需要自己实现迭代。
也就是说,可能有更好的方法来做你想做的事情。