Python combine two lists of unequal length in alte

2019-08-08 15:54发布

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.

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 :(.

4条回答
淡お忘
2楼-- · 2019-08-08 16:16

You might be interested in this itertools recipe:

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']
查看更多
混吃等死
3楼-- · 2019-08-08 16:27

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.

查看更多
Luminary・发光体
4楼-- · 2019-08-08 16:30

Here is the simpler version from the excellent toolz:

>>> interleave([[1,2,3,4,5,6,7,],[0,0,0]])
[1, 0, 2, 0, 3, 0, 4, 5, 6, 7]
查看更多
看我几分像从前
5楼-- · 2019-08-08 16:40

You could use plain map and list comprehension:

>>> [x for t in map(None, a, b) for x in t if x]
['a', 'v', 'b', 'w', 'c', 'x', 'y', 'z']
查看更多
登录 后发表回答