Some built-in to pad a list in python

前端 未结 10 1824
暗喜
暗喜 2020-11-27 14:06

I have a list of size < N and I want to pad it up to the size N with a value.

Certainly, I can use something like the following, but I feel that there sh

10条回答
  •  有刺的猬
    2020-11-27 14:52

    There is no built-in function for this. But you could compose the built-ins for your task (or anything :p).

    (Modified from itertool's padnone and take recipes)

    from itertools import chain, repeat, islice
    
    def pad_infinite(iterable, padding=None):
       return chain(iterable, repeat(padding))
    
    def pad(iterable, size, padding=None):
       return islice(pad_infinite(iterable, padding), size)
    

    Usage:

    >>> list(pad([1,2,3], 7, ''))
    [1, 2, 3, '', '', '', '']
    

提交回复
热议问题