python生成器yield语句not yield

时间:2019-12-13 17:55:12

标签: python generator send yield

这是我正在运行的代码:

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) 

我希望结果如下:

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

但是,我真正得到的是:

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

我认为这可能与在主代码中使用send有关,但无法弄清楚原因。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

根据我的评论,我已经修改了您的主循环

  • 首先,我们发送None以启动生成器并接收第一个值
  • 之后,我们发送一个值并接收下一个值
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

答案 1 :(得分:0)

我设法通过向infinite_Third()添加额外的收益使它按预期工作,但是坦率地说,我不知道为什么会这样。

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

似乎,每次调用send()时,都会将一个额外的None值放置到生成器缓冲区中,而额外的yield看起来就像在消耗它。