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

后端 未结 5 764
伪装坚强ぢ
伪装坚强ぢ 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:08

    Im using a 2d array but the concept is the similar using python 2.x:

    if len(set([len(p) for p in printer])) > 1:
        printer = [column+['']*(max([len(p) for p in printer])-len(column)) for column in printer]
    
    0 讨论(0)
  • 2020-11-22 09:10

    For Python 2.6x use itertools module's izip_longest.

    For Python 3 use zip_longest instead (no leading i).

    >>> list(itertools.izip_longest(a, b, c))
    [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
    
    0 讨论(0)
  • 2020-11-22 09:10

    non itertools My Python 2 solution:

    if len(list1) < len(list2):
        list1.extend([None] * (len(list2) - len(list1)))
    else:
        list2.extend([None] * (len(list1) - len(list2)))
    
    0 讨论(0)
  • 2020-11-22 09:26

    In Python 3 you can use itertools.zip_longest

    >>> list(itertools.zip_longest(a, b, c))
    [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
    

    You can pad with a different value than None by using the fillvalue parameter:

    >>> list(itertools.zip_longest(a, b, c, fillvalue='foo'))
    [('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')]
    

    With Python 2 you can either use itertools.izip_longest (Python 2.6+), or you can use map with None. It is a little known feature of map (but map changed in Python 3.x, so this only works in Python 2.x).

    >>> map(None, a, b, c)
    [('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题