在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
异常的细节,那么您需要自己实现迭代。你知道吗也就是说,可能有更好的方法来做你想做的事情。你知道吗
相关问题 更多 >
编程相关推荐