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

后端 未结 5 935
伪装坚强ぢ
伪装坚强ぢ 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: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)]
    

提交回复
热议问题