如果生成器的长度都相同(包括无限长),则可以
chain together
zip()
:
from itertools import chain
chain.from_iterable(zip(*gen_list))
roundrobin()
example from the
itertools
documentation
:
from itertools import cycle, islice
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
num_active = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while num_active:
try:
for next in nexts:
yield next()
except StopIteration:
num_active -= 1
nexts = cycle(islice(nexts, num_active))
后者的演示:
>>> from itertools import repeat, islice
>>> ones_gen = repeat(1)
>>> twos_gen = repeat(2)
>>> limited_threes_gen = islice(repeat(3), 2)
>>> rrgen = roundrobin(ones_gen, twos_gen, limited_threes_gen)
>>> next(rrgen)
1
>>> next(rrgen)
2
>>> next(rrgen)
3
>>> next(rrgen)
1
>>> next(rrgen)
2
>>> next(rrgen)
3
>>> next(rrgen)
1
>>> next(rrgen)
2
>>> next(rrgen)
1
3号发电机用完了,但另外两台发电机还在继续运转。