在python v.2中交换两个不同长度的列表?

Reb*_*cca 5 python python-2.7

我正在尝试编写一个Python函数,它将两个列表作为参数并对它们进行交错.应保留组件列表的顺序.如果列表的长度不同,则较长列表的元素应最终位于结果列表的末尾.例如,我想把它放在Shell中:

interleave(["a", "b"], [1, 2, 3, 4])
Run Code Online (Sandbox Code Playgroud)

得到这个:

["a", 1, "b", 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

如果你能帮助我,我会很感激.

Blc*_*ght 1

以下是我使用模块各个部分的方法itertools。它适用于任意数量的可迭代对象,而不仅仅是两个:

from itertools import chain, izip_longest # or zip_longest in Python 3
def interleave(*iterables):

    sentinel = object()
    z = izip_longest(*iterables, fillvalue = sentinel)
    c = chain.from_iterable(z)
    f = filter(lambda x: x is not sentinel, c)

    return list(f)
Run Code Online (Sandbox Code Playgroud)