是否有直接将列表/生成器提供给生成器的习惯用法?
lst = [1, 2, 3]
it = my_gen()
next(it)
# can do without i ?
for i in lst:
it.send(i)
更新: 是否可以将 lst 与它链接在一行中,删除 for 和 i ?
请您参考如下方法:
这是一种使用 map 来做到这一点的方法和 deque使用迭代器(此处解释: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)
