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

前端 未结 8 1458
自闭症患者
自闭症患者 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:51

    If we modify @Jon's answer like this

    from itertools import count
    import heapq
    
    [x[1] for x in heapq.merge(izip(count(0, len(b)), a), izip(count(0, len(a)), b))]
    

    It doesn't matter which of a/b is longest

提交回复
热议问题