Is there a zip-like function that pads to longest length in Python?

后端 未结 5 937
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 08:59

Is there a built-in function that works like zip() but that will pad the results so that the length of the resultant list is the length of the longest input rather

5条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 09:27

    non itertools Python 3 solution:

    def zip_longest(*lists):
        def g(l):
            for item in l:
                yield item
            while True:
                yield None
        gens = [g(l) for l in lists]    
        for _ in range(max(map(len, lists))):
            yield tuple(next(g) for g in gens)
    

提交回复
热议问题