<p>对于3.3之前的Python,请使用嵌套For循环。你知道吗</p>
<pre><code>def interleave(*args):
for items in zip(*args):
for item in items:
yield item
</code></pre>
<p>对于python3.3+,您可以使用<code>yield from</code>表示<a href="https://docs.python.org/3/whatsnew/3.3.html#pep-380" rel="nofollow noreferrer">generator delegation</a>,这是上面提到的语法糖。你知道吗</p>
<pre><code>def interleave(*args):
for items in zip(*args):
yield from items
</code></pre>
<p>最后,如果您需要一个允许不同长度列表的更通用的解决方案,请使用<a href="https://docs.python.org/3/library/itertools.html#itertools-recipes" rel="nofollow noreferrer">itertools recipes</a>中的<code>roundrobin</code>函数。你知道吗</p>
<pre><code>def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') > A D E B F C"
# Recipe credited to George Sakkis
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:
# Remove the iterator we just exhausted from the cycle.
num_active -= 1
nexts = cycle(islice(nexts, num_active))
</code></pre>