python的yield是否意味着继续?
我有一个 for 循环来检查一系列条件。在每次迭代中,它应该仅针对其中一个条件产生输出。最终产量是默认值,以防所有条件都不成立。我是否必须在每个收益块后面添加一个继续?
def function():
for ii in aa:
if condition1(ii):
yield something1
yield something2
yield something3
continue
if condition2(ii):
yield something4
continue
#default
yield something5
continue
I have a for loop that checks a series of conditions. On each iteration, it should yield output for only one of the conditions. The final yield is a default, in case none of the conditions are true. Do I have to put a continue after each block of yields?
def function():
for ii in aa:
if condition1(ii):
yield something1
yield something2
yield something3
continue
if condition2(ii):
yield something4
continue
#default
yield something5
continue
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不,yield 并不意味着继续,它只是从下一行开始,下一次。一个简单的例子演示了
This 打印 0,1,2 但如果yield 继续,它不会
NO, yield doesn't imply continue, it just starts at next line, next time. A simple example demonstrates that
This prints 0,1,2 but if yield continues, it won't
我建议使用 elif 和 else 语句,而不是使用 continue 语句:
这对我来说似乎更具可读性
Instead of using the
continue
statement I would suggest using theelif
andelse
statments:This seems much more readable to me
Python 中的
yield
停止执行并返回值。当再次调用迭代器时,它会在yield
语句之后直接继续执行。例如,定义为的生成器将依次返回
1
然后2
。换句话说,需要继续
。然而,在这种情况下,flashk 所描述的elif
和else
绝对是正确的工具。yield
in Python stops execution and returns the value. When the iterator is invoked again it continues execution directly after theyield
statement. For instance, a generator defined as:would return
1
then2
sequentially. In other words, thecontinue
is required. However, in this instance,elif
andelse
as flashk described are definitely the right tools.continue
会跳过剩余的代码块,但是当在生成器上再次调用next()
时,会执行yield
之后的代码块。yield
的作用就像在某个点暂停执行。continue
skips the remaining code block, but the code block afteryield
is executed whennext()
is called again on the generator.yield
acts like pausing execution at certain point.这个方式比较清晰了,希望有帮助,也感谢Anurag Uniyal。
----------- 运行后 ------------
This way is more clear, hope it helps, also thanks Anurag Uniyal.
----------- after run ------------
如果某事是简单值并且条件是检查相等性,我更愿意进行此“案例结构”字典查找:
If the something is simple value and conditions are checks for equality, I would prefer to make this "case structure" dictionary lookup: