在for循环中检索给定给StopIteration的参数



在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异常的细节,则需要自己实现迭代。

也就是说,可能有更好的方法来做你想做的事情。

最新更新