Some built-in to pad a list in python

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

    You could also use a simple generator without any build ins. But I would not pad the list, but let the application logic deal with an empty list.

    Anyhow, iterator without buildins

    def pad(iterable, padding='.', length=7):
        '''
        >>> iterable = [1,2,3]
        >>> list(pad(iterable))
        [1, 2, 3, '.', '.', '.', '.']
        '''
        for count, i in enumerate(iterable):
            yield i
        while count < length - 1:
            count += 1
            yield padding
    
    if __name__ == '__main__':
        import doctest
        doctest.testmod()
    

提交回复
热议问题