python generator yield statement not yield

跟風遠走 提交于 2021-02-19 01:49:20

问题


Here is code I am running:

def infinite_Third() -> Generator:
    num = 1
    while True:
        if num % 3 ==0:
            i = (yield num)
            if i is not None:
                num = i
        num += 1 

if __name__=='__main__':
    third_gen = infinite_Third()
    for i in third_gen:
        print(f"it is {i}")          
        if i>1000:
            break    
        third_gen.send(10*i+1) 

I am expecting to see results as:

it is 3
it is 33
it is 333
it is 3333

However, what I really get is:

it is 3
it is 36
it is 366
it is 3666

I think this might be related to using send in the main code, but couldn't figure out why. Can anyone help?


回答1:


Follow up from my comment, I've modified your main loop

  • First, we send a None to start the generator and receive the first value
  • After that, we send one value and receive the next one
if __name__ == '__main__':
    third_gen = infinite_Third()
    i = third_gen.send(None)
    while True:
        print(f"it is {i}")
        i = third_gen.send(10*i+1)
        if i > 1000:
            break



回答2:


I managed to make it working as you expect by adding extra yield to infinite_Third() but frankly i don't know why it works.

def infinite_Third() -> Generator:
    num = 1
    while True:
        if num % 3 ==0:
            i = yield num
            if i is not None:
                num = i
            yield
        num += 1

It seems that, every time send() is called, an extra None value is put to the generator buffer and extra yield looks like consuming that.



来源:https://stackoverflow.com/questions/59327603/python-generator-yield-statement-not-yield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!