Pythonic way to combine two lists in an alternating fashion?

前端 未结 21 3069
误落风尘
误落风尘 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 16:52

    An alternative in a functional & immutable way (Python 3):

    from itertools import zip_longest
    from functools import reduce
    
    reduce(lambda lst, zipped: [*lst, *zipped] if zipped[1] != None else [*lst, zipped[0]], zip_longest(list1, list2),[])
    
    0 讨论(0)
  • 2020-11-22 16:54

    My take:

    a = "hlowrd"
    b = "el ol"
    
    def func(xs, ys):
        ys = iter(ys)
        for x in xs:
            yield x
            yield ys.next()
    
    print [x for x in func(a, b)]
    
    0 讨论(0)
  • 2020-11-22 16:55

    Here's one way to do it by slicing:

    >>> list1 = ['f', 'o', 'o']
    >>> list2 = ['hello', 'world']
    >>> result = [None]*(len(list1)+len(list2))
    >>> result[::2] = list1
    >>> result[1::2] = list2
    >>> result
    ['f', 'hello', 'o', 'world', 'o']
    
    0 讨论(0)
  • 2020-11-22 16:55

    Stops on the shortest:

    def interlace(*iters, next = next) -> collections.Iterable:
        """
        interlace(i1, i2, ..., in) -> (
            i1-0, i2-0, ..., in-0,
            i1-1, i2-1, ..., in-1,
            .
            .
            .
            i1-n, i2-n, ..., in-n,
        )
        """
        return map(next, cycle([iter(x) for x in iters]))
    

    Sure, resolving the next/__next__ method may be faster.

    0 讨论(0)
  • 2020-11-22 16:56
    def combine(list1, list2):
        lst = []
        len1 = len(list1)
        len2 = len(list2)
    
        for index in range( max(len1, len2) ):
            if index+1 <= len1:
                lst += [list1[index]]
    
            if index+1 <= len2:
                lst += [list2[index]]
    
        return lst
    
    0 讨论(0)
  • 2020-11-22 16:57
    from itertools import chain
    list(chain(*zip('abc', 'def')))  # Note: this only works for lists of equal length
    ['a', 'd', 'b', 'e', 'c', 'f']
    
    0 讨论(0)
提交回复
热议问题