Populating a list/array by index in Python?

后端 未结 7 1902
一整个雨季
一整个雨季 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:17

    Building on top of Triptych.. If you want a list of arbitrary dimensions

    class dynamiclist(list):
        """ List not needing pre-initialization
    
        Example:
            l = dynamiclist()
            l[20][1] = 10
            l[21][1] = 20
        """
    
        def __setitem__(self, index, value):
            size = len(self)
            if index >= size:
                self.extend(dynamiclist() for _ in range(size, index + 1))
    
            list.__setitem__(self, index, value)
    
        def __getitem__(self, index):
            size = len(self)
            if index >= size:
                self.extend(dynamiclist() for _ in range(size, index + 1))  # allows dimensions > 1
    
            return list.__getitem__(self, index)
    

    Example

    l = dynamiclist()
    l[20][1] = 10
    l[21][1] = 20
    

提交回复
热议问题