Pythonic way to combine two lists in an alternating fashion?

前端 未结 21 3072
误落风尘
误落风尘 2020-11-22 16:13

I have two lists, the first of which is guaranteed to contain exactly one more item than the second. I would like to know the most Pythonic way to create a

相关标签:
21条回答
  • 2020-11-22 17:02

    How about numpy? It works with strings as well:

    import numpy as np
    
    np.array([[a,b] for a,b in zip([1,2,3],[2,3,4,5,6])]).ravel()
    

    Result:

    array([1, 2, 2, 3, 3, 4])
    
    0 讨论(0)
  • 2020-11-22 17:04

    I'm too old to be down with list comprehensions, so:

    import operator
    list3 = reduce(operator.add, zip(list1, list2))
    
    0 讨论(0)
  • 2020-11-22 17:05

    This should do what you want:

    >>> iters = [iter(list1), iter(list2)]
    >>> print list(it.next() for it in itertools.cycle(iters))
    ['f', 'hello', 'o', 'world', 'o']
    
    0 讨论(0)
  • 2020-11-22 17:06

    Without itertools and assuming l1 is 1 item longer than l2:

    >>> sum(zip(l1, l2+[0]), ())[:-1]
    ('f', 'hello', 'o', 'world', 'o')
    

    Using itertools and assuming that lists don't contain None:

    >>> filter(None, sum(itertools.izip_longest(l1, l2), ()))
    ('f', 'hello', 'o', 'world', 'o')
    
    0 讨论(0)
  • 2020-11-22 17:08

    I know the questions asks about two lists with one having one item more than the other, but I figured I would put this for others who may find this question.

    Here is Duncan's solution adapted to work with two lists of different sizes.

    list1 = ['f', 'o', 'o', 'b', 'a', 'r']
    list2 = ['hello', 'world']
    num = min(len(list1), len(list2))
    result = [None]*(num*2)
    result[::2] = list1[:num]
    result[1::2] = list2[:num]
    result.extend(list1[num:])
    result.extend(list2[num:])
    result
    

    This outputs:

    ['f', 'hello', 'o', 'world', 'o', 'b', 'a', 'r'] 
    
    0 讨论(0)
  • 2020-11-22 17:08

    Here's a one liner that does it:

    list3 = [ item for pair in zip(list1, list2 + [0]) for item in pair][:-1]

    0 讨论(0)
提交回复
热议问题