Some built-in to pad a list in python

前端 未结 10 1794
暗喜
暗喜 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()
    
    0 讨论(0)
  • 2020-11-27 14:27

    you can use * iterable unpacking operator:

    N = 5
    a = [1]
    
    pad_value = ''
    pad_size = N - len(a)
    
    final_list = [*a, *[pad_value] * pad_size]
    print(final_list)
    

    output:

    [1, '', '', '', '']
    
    0 讨论(0)
  • 2020-11-27 14:27
    extra_length = desired_length - len(l)
    l.extend(value for _ in range(extra_length))
    

    This avoids any extra allocation, unlike any solution that depends on creating and appending the list [value] * extra_length. The "extend" method first calls __length_hint__ on the iterator, and extends the allocation for l by that much before filling it in from the iterator.

    0 讨论(0)
  • 2020-11-27 14:28

    I think this approach is more visual and pythonic.

    a = (a + N * [''])[:N]
    
    0 讨论(0)
  • 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, '')
    
    0 讨论(0)
  • 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, '', '', '', '']
    
    0 讨论(0)
提交回复
热议问题