开发者

Does python yield imply continue?

开发者 https://www.devze.com 2023-01-08 07:33 出处:网络
I have a for loop that checks a series of conditions.O开发者_如何学编程n each iteration, it should yield output for only one of the conditions.The final yield is a default, in case none of the conditi

I have a for loop that checks a series of conditions. O开发者_如何学编程n 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


NO, yield doesn't imply continue, it just starts at next line, next time. A simple example demonstrates that

def f():
    for i in range(3):
        yield i
        print i,

list(f())

This prints 0,1,2 but if yield continues, it won't


Instead of using the continue statement I would suggest using the elif and else statments:

def function():
    for ii in aa:
       if condition1(ii):
           yield something1
           yield something2
           yield something3

       elif condition2(ii):
           yield something4

       else: #default
           yield something5

This seems much more readable to me


yield in Python stops execution and returns the value. When the iterator is invoked again it continues execution directly after the yield statement. For instance, a generator defined as:

def function():
    yield 1
    yield 2

would return 1 then 2 sequentially. In other words, the continue is required. However, in this instance, elif and else as flashk described are definitely the right tools.


continue skips the remaining code block, but the code block after yield is executed when next() is called again on the generator. yield acts like pausing execution at certain point.


This way is more clear, hope it helps, also thanks Anurag Uniyal.

def f():
    for i in range(3):
        yield i
        print(i+10)

list(f())

----------- after run ------------

10
11
12
[0, 1, 2]


If the something is simple value and conditions are checks for equality, I would prefer to make this "case structure" dictionary lookup:

ii_dict={'a':('somethinga1','somethinga2','somethinga3'),'b':('somethingb1',)}
ii_default = ('somethingdefault',)
aa='abeabbacd'

def function():
    return (value
           for ii in aa
           for value in (ii_dict[ii] if ii in ii_dict else ii_default))

for something in function(): print something
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号