是否有直接将列表/生成器提供给生成器的习惯用法?
lst = [1, 2, 3]
it = my_gen()
next(it)
# can do without i ?
for i in lst:
it.send(i)
UPD:
是否可以将lst链接到一行,删除for
和i
?
答案 0 :(得分:2)
这是使用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)