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

2024-04-25 17:13:02 发布

您现在位置:Python中文网/ 问答频道 /正文

在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

Tags: inmostforreturndefresultcallnext
1条回答
网友
1楼 · 发布于 2024-04-25 17:13:02

没有;for循环吞下StopIteration异常。如果您关心StopIteration异常的细节,那么您需要自己实现迭代。你知道吗

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

相关问题 更多 >