使用来自 itertools的roundrobin
配方:
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
演示:
>>> x = ['abc', 'd', 'efgh']
>>> from itertools import cycle, islice
>>> list(roundrobin(*x))
['a', 'd', 'e', 'b', 'f', 'c', 'g', 'h']
另一种选择是使用itertools.izip_longest
and itertools.chain.from_iterable
:
>>> from itertools import izip_longest, chain
>>> x = ['abc', 'd', 'efgh']
>>> sentinel = object()
>>> [y for y in chain.from_iterable(izip_longest(*x, fillvalue=sentinel))
if y is not sentinel]
['a', 'd', 'e', 'b', 'f', 'c', 'g', 'h']