简体   繁体   English

Python以交替方式合并两个长度不等的列表

[英]Python combine two lists of unequal length in alternating fashion

I have a two lists, and I want to combine them in an alternating fashion, until one runs out, and then I want to keep adding elements from the longer list. 我有两个列表,我想以一种交替的方式组合它们,直到一个列表用完,然后我要继续从较长的列表中添加元素。

Aka. ka

list1 = [a,b,c]

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

result = [a,v,b,w,c,x,y,z]

Similar to this question ( Pythonic way to combine two lists in an alternating fashion? ), except in these the lists stop combining after the first list has run out :(. 类似于此问题(以Python的方式以交替方式组合两个列表的方式? ),除了在第一个列表用尽(:。

You might be interested in this itertools recipe : 您可能对此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))

For example: 例如:

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

Here is the simpler version from the excellent toolz : 这是出色的toolz的简单版本:

>>> interleave([[1,2,3,4,5,6,7,],[0,0,0]])
[1, 0, 2, 0, 3, 0, 4, 5, 6, 7]

My solution: 我的解决方案:

result = [i for sub in zip(list1, list2) for i in sub]

EDIT: Question specifies the longer list should continue at end of shorter list, which this answer does not do. 编辑:问题规定了较长的名单应继续在更短的名单,其中这个答案并不做结束。

You could use plain map and list comprehension: 您可以使用纯map和列表理解:

>>> [x for t in map(None, a, b) for x in t if x]
['a', 'v', 'b', 'w', 'c', 'x', 'y', 'z']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM