Python combine two lists of unequal length in alte

2019-08-08 16:13发布

问题:

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

回答1:

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]


回答2:

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:

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.



回答4:

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']