Interleave multiple lists of the same length in Python

后端 未结 9 1465
刺人心
刺人心 2020-11-22 10:11

In Python, is there a good way to interleave two lists of the same length?

Say I\'m given [1,2,3] and [10,20,30]. I\'d like to transform th

9条回答
  •  囚心锁ツ
    2020-11-22 10:45

    I needed a way to do this with lists of different sizes which the accepted answer doesn't address.

    My solution uses a generator and its usage looks a bit nicer because of it:

    def interleave(l1, l2):
        iter1 = iter(l1)
        iter2 = iter(l2)
        while True:
            try:
                if iter1 is not None:
                    yield next(iter1)
            except StopIteration:
                iter1 = None
            try:
                if iter2 is not None:
                    yield next(iter2)
            except StopIteration:
                iter2 = None
            if iter1 is None and iter2 is None:
                raise StopIteration()
    

    And its usage:

    >>> a = [1, 2, 3, 4, 5]
    >>> b = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    >>> list(interleave(a, b))
    [1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 'e', 'f', 'g']
    >>> list(interleave(b, a))
    ['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5, 'f', 'g']
    

提交回复
热议问题