在 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
异常的详细信息,您需要自己实现迭代。
也就是说,可能有更好的方法来完成您想做的任何事情。
关于python - 检索 for 循环中赋予 StopIteration 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23901676/