Python List - “reserving” space ( ~ resizing)

后端 未结 4 1225
既然无缘
既然无缘 2021-01-03 22:42

I am given a list l and I want to do assignment:

l[index] = val

But there might be a case when the list is too small.

相关标签:
4条回答
  • 2021-01-03 23:15

    If you're sure that a list -- and not, say, a dict -- is the best data structure for your use case, I propose the following class:

    class rlist(list):
      def __init__(self, default):
        self._default = default
      def __setitem__(self, key, value):
        if key >= len(self):
          self += [self._default] * (key - len(self) + 1)
        super(rlist, self).__setitem__(key, value)
    
    l = rlist(0)
    print(l)
    l[10] = 20
    print(l)
    l[5] = 14
    print(l)
    

    This class checks whether the index being assigned to is beyond the current length of the list, and automatically expands the list as required.

    The code is compatible with both Python 2 and 3 (tested with 2.6.5 and 3.1.2).

    This class could be handy if the structure is dense and you need to find the element by index as quickly as possible. If the structure is sparse, you should probably consider using a dictionary.

    0 讨论(0)
  • 2021-01-03 23:18

    Try this:

    def ResizeList(some_list, length, null_item = None): 
        return some_list + [null_item 
                            for item in range(length - len(lst))]
    
    0 讨论(0)
  • 2021-01-03 23:34

    Perhaps this does what you want:

    def resize(l, newsize, filling=None):                                                                                  
        if newsize > len(l):                                                                                 
            l.extend([filling for x in xrange(len(l), newsize)])                                                 
        else:                                                                                                
            del l[newsize:]                  
    
    0 讨论(0)
  • I came up with something that uses itertool.repeat().

    import itertools
    
    def assign(lst, idx, value, fill=None):
        diff = len(lst) - idx
        if diff >= 0:
            lst[idx] = value
        else:
            lst.extend(itertools.repeat(fill, -diff))
            lst.append(value)
    

    That have the following behaviour:

    >>> l = [0, 1, 2, 3, 4]
    >>> assign(l, 2, 'new')
    >>> l
    [0, 1, 'new', 3, 4]
    >>> assign(l, 8, 'new')
    >>> l
    [0, 1, 'new', 3, 4, None, None, None, 'new']
    >>> assign(l, 10, 'new', fill=[])
    >>> l
    [0, 1, 'new', 3, 4, None, None, None, 'new', [], 'new']
    

    Does this work for you?

    Edit: Since the question was updated I've updated the answer.

    0 讨论(0)
提交回复
热议问题