Populating a list/array by index in Python?

后端 未结 7 1898
一整个雨季
一整个雨季 2021-01-31 17:02

Is this possible:

myList = []

myList[12] = \'a\'
myList[22] = \'b\'
myList[32] = \'c\'
myList[42] = \'d\'

When I try, I get:

#         


        
7条回答
  •  灰色年华
    2021-01-31 17:18

    Here's a quick list wrapper that will auto-expand your list with zeros if you attempt to assign a value to a index past it's length.

    class defaultlist(list):
    
       def __setitem__(self, index, value):
          size = len(self)
          if index >= size:
             self.extend(0 for _ in range(size, index + 1))
    
          list.__setitem__(self, index, value)
    

    Now you can do this:

    >>> a = defaultlist([1,2,3])
    >>> a[1] = 5
    [1,5,3]
    >>> a[5] = 10
    [1,5,3,0,0,10]
    

提交回复
热议问题