python - 如果没有产生数据,则在生成器内引发错误
问题描述
yield
如果没有发生,我想在生成器中引发错误。以下是我的问题的一个非常简化的示例:
def test1():
for i in range(1, 28):
if i % 5 == 0:
yield str(i)
raise CustomEXception
def test2(x):
for i in range(1, 38):
if i % x == 0:
yield str(i)
raise CustomEXception
a = test1()
b = test2()
和实际上是循环数据test1
、test2
搜索匹配、操作数据和yield
. 如果没有产生数据,则会引发错误。
for w,q in itertools.products(a, b):
try:
print(w + q)
# do some more operation with w, q
except CustomException:
# do some more checking
生成器的结果用于创建笛卡尔积。
问题是这不起作用,引发了异常,之前没有任何结果。
解决方案
此外,您必须确保您的函数仅在raise
没有异常的情况下才会出现yields
def test2(x):
fail = True
for i in range(1,38):
if i % x == 0:
fail = False
yield str(i)
if fail:
raise ValueError
这样,如果有一个或多个,yields
则不会引发异常product
并将生成自己的生成器。
推荐阅读
- php - PHP AJAX Jquery 日历需要重置 beforeShowDay 值吗?
- r - 在多列 R 中查找具有最多匹配的列
- javascript - 等待 Firestore 集合/文档上的循环结束,然后在 Node.js 中发送输出
- angular - mat-tab 标签 flex wrap 响应式
- node.js - nativescript-socketio 未连接到 Node Js 服务器
- go - Windows exec runner 无法克隆 git repo
- javascript - WebGLInput.captureAllKeyboardInput 奇怪的行为。可以启用,但不能禁用
- java - 使用 java split 从文件中解析日期
- r - 对时间序列进行降序排序
- javascript - 如何为 Material UI 模板使用从右到左的选项?