How to elegantly interleave two lists of uneven length in python?

前端 未结 8 1431
自闭症患者
自闭症患者 2021-01-04 06:13

I want to merge two lists in python, with the lists being of different lengths, so that the elements of the shorter list are as equally spaced within the final list as possi

8条回答
  •  甜味超标
    2021-01-04 06:50

    A variant of @Jon Clements answer using more_itertools.collate with explanation.

    Given

    import itertools as it
    
    import more_itertools as mit
    
    
    a, b = range(1, 5), ["a", "b"]
    

    Code

    first = enumerate(a)
    second = zip(it.count(0, len(a) // len(b)), b)
    [x for i, x in mit.collate(first, second, key=lambda x: x[0])]
    # [1, 'a', 2, 3, 'b', 4] 
    

    Details

    This answer is updated to use with Python 3.

    first and second are iterables of tuples, each tuple comprising a position-element pair.

    list(first)
    # [(0, 1), (1, 2), (2, 3), (3, 4)]
    
    list(second)
    # [(0, 'a'), (2, 'b')]
    

    more_itertools.collate() wraps heapq.merge(), which merges the pre-sorted first and second iterables in order. In the final list comprehension, the key is the sorting function while the last element in each tuple in returned.

    Install this third-party package via > pip install more_itertools or use heapq.merge() directly.

提交回复
热议问题