Some built-in to pad a list in python

前端 未结 10 1973
暗喜
暗喜 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:36

    more-itertools is a library that includes a special padded tool for this kind of problem:

    import more_itertools as mit
    
    list(mit.padded(a, "", N))
    # [1, '', '', '', '']
    

    Alternatively, more_itertools also implements Python itertools recipes including padnone and take as mentioned by @kennytm, so they don't have to be reimplemented:

    list(mit.take(N, mit.padnone(a)))
    # [1, None, None, None, None]
    

    If you wish to replace the default None padding, use a list comprehension:

    ["" if i is None else i for i in mit.take(N, mit.padnone(a))]
    # [1, '', '', '', '']
    

提交回复
热议问题