Interleave multiple lists of the same length in Python

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

    Given

    a = [1, 2, 3]
    b = [10, 20, 30]
    c = [100, 200, 300, 999]
    

    Code

    Assuming lists of equal length, you can get an interleaved list with itertools.chain and zip:

    import itertools
    
    
    list(itertools.chain(*zip(a, b)))
    # [1, 10, 2, 20, 3, 30]
    

    Alternatives

    itertools.zip_longest

    More generally with unequal lists, use zip_longest (recommended):

    [x for x in itertools.chain(*itertools.zip_longest(a, c)) if x is not None]
    # [1, 100, 2, 200, 3, 300, 999]
    

    Many lists can safely be interleaved:

    [x for x in itertools.chain(*itertools.zip_longest(a, b, c)) if x is not None]
    # [1, 10, 100, 2, 20, 200, 3, 30, 300, 999]
    

    more_itertools+

    A library that ships with the roundrobin itertools recipe, interleave and interleave_longest.

    import more_itertools
    
    
    list(more_itertools.roundrobin(a, b))
    # [1, 10, 2, 20, 3, 30]
    
    list(more_itertools.interleave(a, b))
    # [1, 10, 2, 20, 3, 30]
    
    list(more_itertools.interleave_longest(a, c))
    # [1, 100, 2, 200, 3, 300, 999]
    

    yield from

    Finally, for something interesting in Python 3 (though not recommended):

    list(filter(None, ((yield from x) for x in zip(a, b))))
    # [1, 10, 2, 20, 3, 30]
    
    list([(yield from x) for x in zip(a, b)])
    # [1, 10, 2, 20, 3, 30]
    

    +Install using pip install more_itertools

提交回复
热议问题