Some built-in to pad a list in python

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

    a += [''] * (N - len(a))
    

    or if you don't want to change a in place

    new_a = a + [''] * (N - len(a))
    

    you can always create a subclass of list and call the method whatever you please

    class MyList(list):
        def ljust(self, n, fillvalue=''):
            return self + [fillvalue] * (n - len(self))
    
    a = MyList(['1'])
    b = a.ljust(5, '')
    

提交回复
热议问题