如何在for循环中将值传递给生成器?

时间:2016-09-27 01:53:02

标签: python generator

我知道您可以使用.send(value)向生成器发送值。我也知道你可以在for循环中迭代生成器。是否可以在for循环中迭代它时将值传递给生成器?

我想做的是

def example():
    previous = yield
    for i range(0,10):
        previous = yield previous*i

t = example()
for value in example"...pass in a value?...":
    "...do something with the result..."

2 个答案:

答案 0 :(得分:1)

技术上可以,但结果会令人困惑。例如:

def example():
    previous = (yield)
    for i in range(1,10):
        received = (yield previous)
        if received is not None:
            previous = received*i


t = example()
for i, value in enumerate(t):
  t.send(i)
  print value

输出:

None
0
2
8
18

Dave Beazley在协同程序上写了amazing article tldr;不要在同一函数中混合生成器和协同程序

答案 1 :(得分:0)

好的,所以我明白了。诀窍是创建一个额外的生成器,将t.send(value)包裹在for循环(t.send(value) for value in [...])中。

def example():
    previous = yield
    for i in range(0,10):
        previous = yield previous * i

t = examplr()
t.send(None)
for i in (t.send(i) for i in ["list of objects to pass in"]):
    print i