python - 检索 for 循环中赋予 StopIteration 的参数

标签 python for-loop python-3.x generator

在 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/

相关文章:

python - 查找与另一个大列表重叠/相交的大列表的子集

python - 如何在 Python 中对这 2 个循环进行向量化?

java - 导致我的程序在 if-else 语句后无法继续运行的字符串数组 - java

python - 找出奇数位置的最优雅方法

python - 计算给定Python中另一个类的对象的周长

python - 使用 Selenium 和 Python 使用 Chromium 进行测试

python - SQL Alchemy IN 查询中出现 PG8000 异常 : invalid input syntax for type integer: "{2,3,5,6,7}"

python - Mojave 上的 pyenv 在安装 3.5.6、3.6.7 时抛出未声明的标识符 'CLOCK_REALTIME' 和其他错误

python - 将包含数字和一些破折号的列转为 int?

使用 for 循环创建链表