使用roundrobin
recipe从itertools:
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
和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']
我会'y不是哨兵'...以防万一'y'有一个时髦的定义'__ne__'。 (当然,这对弦乐无关紧要,但这是一个很好的习惯)。 – mgilson
@mgilson感谢您解决这个问题,实际上在我的真实代码中使用了'not',但是在这里使用了'!=',因为我对此有点怀疑。 ;-) –
考虑你的观众:) – beroe