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

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

    If we want to do this without itertools:

    def interleave(l1, l2, default=None):  
        max_l = max(len(l1), len(l2))
        data  = map(lambda x: x + [default] * (max_l - len(x)), [l1,l2])
        return [data[i%2][i/2] for i in xrange(2*max_l)]
    

    Ahh, missed the equally spaced part. This was for some reason marked as duplicate with a question that didn't require equally spaced in the presence of differing list lengths.

提交回复
热议问题