这使用以下内容组成了一个列表理解zip_longest
from 迭代工具(这是标准库的一部分)将两个列表中的项目交错成一个tuple
,默认情况下使用None
作为填充值。
这也使用chain
也来自itertools
压平列表。
最后过滤掉None
清单中的项目:
from itertools import chain, zip_longest
def twolists(l1, l2):
return [x for x in chain(*zip_longest(l1, l2)) if x is not None]
或者按照 @EliKorvigo 的建议,使用itertools.chain.from_iterable
对于惰性迭代:
def twolists(l1, l2):
return [x for x in chain.from_iterable(zip_longest(l1, l2)) if x is not None]
Testing
In [56]: twolists([0, 1], ['w', 'x'])
Out[56]: [0, 'w', 1, 'x']
In [57]: twolists([0, 1], ['w', 'x', 'y', 'z'])
Out[57]: [0, 'w', 1, 'x', 'y', 'z']
In [74]: twolists([0, 1, 2, 3], ['w', 'x'])
Out[74]: [0, 'w', 1, 'x', 2, 3]