使用generator.send()在一行中使用多个项目

时间:2017-01-07 08:40:09

标签: python generator

是否有直接将列表/生成器提供给生成器的习惯用法?

lst = [1, 2, 3]
it = my_gen()
next(it)
# can do without i ?
for i in lst:
  it.send(i)

UPD: 是否可以将lst链接到一行,删除fori

1 个答案:

答案 0 :(得分:2)

这是使用mapdeque来使用迭代器的方法(在此处解释:itertools consume recipie) :

from collections import deque

def my_gen():
    data = ''
    while data is not None:
        print(data)
        data = yield data
    print(data)
    yield data

lst = [1, 2, 3]
it = my_gen()
next(it)  # priming the generator still needs to be done

deque(map(it.send, lst), maxlen=0)