作者热门文章
- html - 我的下拉菜单的内容关闭得太快
- c# - 使用 Html Agility Pack 从网页中的表中获取值而不使用 "SelectNode'
- html - 内容容器下的 CSS 下拉菜单
- html - 如何停止嵌套列表重叠父列表?
我写了一个生成器,它返回值的元组:
import numpy as np
def mygenerator():
data = np.arange(10)
data = np.reshape(data, (-1, 2))
for row in data:
yield row[0], row[1]
generator = mygenerator()
while True:
a, b = generator.__next__()
print("a: ", a, "b: ", b)
for ... in
的情况下使用它.那么如何检测世代结束呢?
最佳答案
生成器会抛出异常 StopIteration
当它耗尽时。您可以使用 try
捕获异常… except
语句和退出循环发生时:
while True:
try:
a, b = next(generator)
except StopIteration:
break
print("a: ", a, "b: ", b)
for
环形?看起来:
for a, b in generator:
print("a: ", a, "b: ", b)
关于python - 如何在 Python 中显式检测生成器端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46173039/
我是一名优秀的程序员,十分优秀!