Python以交替的方式组合了两个不等长的列表

Bet*_*eth 1 python list alternation python-2.7

我有两个列表,我希望以交替方式组合它们,直到一个用完,然后我想继续添加更长列表中的元素.

阿卡.

list1 = [a,b,c]

list2 = [v,w,x,y,z]

result = [a,v,b,w,c,x,y,z]
Run Code Online (Sandbox Code Playgroud)

类似于这个问题(Pythonic方式以交替的方式组合两个列表?),除了这些列表在第一个列表用完后停止组合:(.

jon*_*rpe 5

您可能对此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))
Run Code Online (Sandbox Code Playgroud)

例如:

>>> from itertools import cycle, islice
>>> list1 = list("abc")
>>> list2 = list("uvwxyz")
>>> list(roundrobin(list1, list2))
['a', 'u', 'b', 'v', 'c', 'w', 'x', 'y', 'z']
Run Code Online (Sandbox Code Playgroud)


mdu*_*ant 5

这是来自优秀toolz的简单版本:

>>> interleave([[1,2,3,4,5,6,7,],[0,0,0]])
[1, 0, 2, 0, 3, 0, 4, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)