Interleave multiple lists of the same length in Python

后端 未结 9 1564
刺人心
刺人心 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:23

    Alternative:

    >>> l1=[1,2,3]
    >>> l2=[10,20,30]
    >>> [y for x in map(None,l1,l2) for y in x if y is not None]
    [1, 10, 2, 20, 3, 30]
    

    This works because map works on lists in parallel. It works the same under 2.2. By itself, with None as the called functions, map produces a list of tuples:

    >>> map(None,l1,l2,'abcd')
    [(1, 10, 'a'), (2, 20, 'b'), (3, 30, 'c'), (None, None, 'd')]
    

    Then just flatten the list of tuples.

    The advantage, of course, is map will work for any number of lists and will work even if they are different lengths:

    >>> l1=[1,2,3]
    >>> l2=[10,20,30]
    >>> l3=[101,102,103,104]
    >>> [y for x in map(None,l1,l2,l3) for y in x if y in not None]
    [1, 10, 101, 2, 20, 102, 3, 30, 103, 104]
    

提交回复
热议问题