您可以使用得到您需要的结果zip_longest https://docs.python.org/3/library/itertools.html#itertools.zip_longest, chain https://docs.python.org/3/library/itertools.html#itertools.chain and filter https://docs.python.org/3/library/functions.html#filter一起。
让我们调用查询集p
and q
。然后你会这样做:
# Python 3.x
from itertools import chain, zip_longest
combined = list(filter(lambda x: x is not None, chain(*zip_longest(p, q))))
# Python 2.7
from itertools import chain, ifilter, izip_longest
combined = list(ifilter(lambda x: x is not None, chain(*izip_longest(p, q))))
让我们解释一下它是如何工作的。第一的,zip_longest
(izip_longest
在 Python 中 2) 将查询集压缩在一起。你要zip_longest
代替zip
,以便在较短的查询集完成后继续输出。
这会创建一个可迭代的对象,例如:
((p[0], q(0)), (p[1], q[1]), (p[2], q[2]), ..., (p[9], q[9]), (p[10], None))
请注意,这是一个可迭代的元组,但您需要一个平面列表。那么接下来我们使用chain
, 使用*
运算符来解压结果zip_longest
.
这创建了一个可迭代的like。
(p[0], q[0], p[1], q[1], ..., p[9], q[9], p[10], None)
这几乎就是我们想要的,但我们已经有了None
如果一个查询集比另一个查询集短,则在末尾添加 s。我们可以用以下方法摆脱它们filter
(ifilter
在Python 2)。