【问题标题】:Create List with variable length in Python在 Python 中创建具有可变长度的列表
【发布时间】:2019-10-28 11:25:12
【问题描述】:
testList= []
testList[12]= 31
testList[23]= 1337

Error: IndexError: list assignment index out of range

基本上我有唯一的整数,我想将列表用于哈希函数 h(x)= x(因为它们是唯一的)

我可以这样初始化长度:

testList= [0 for i in range(50)]

但是我必须修复随着时间增加的大小和唯一编号。可以将大小设置为例如 1-2Mio 还是有办法动态执行此操作? Java 中的 ArrayList 是动态追加和删除的,Python 中的列表也是如此。

谢谢!

【问题讨论】:

  • 改用dict:testDict={}

标签: python arrays variable-length-array


【解决方案1】:

也许你需要一个dict

testList = {}
testList[12]= 31
testList[23]= 1337

print(testList)
print(testList[23])

输出:

{12: 31, 23: 1337}
1337

【讨论】:

    【解决方案2】:

    如果您不想使用字典(我认为您应该这样做),您可以创建自己的自动扩展列表:

    class defaultlist(list):
    
        def __init__(self,defData):
            self.defData = defData
    
        def _getDefault(self):
            if isinstance(self.defData,type):
                return self.defData()
            return self.defData
    
        def __getitem__(self,index):
            if index >= len(self):
                return self._getDefault()
            return super.__getitem__(index)
    
        def __setitem__(self,index,value):
            while index>=len(self):
                self.append(self._getDefault())
            list.__setitem__(self,index,value)
    
    
    testList = defaultlist(0) # need to provide a default value for auto-created items
    testList[12]= 31
    testList[23]= 1337
    
    print(testList)
    # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1337]
    

    【讨论】:

      猜你喜欢
      • 2019-03-01
      • 2019-03-20
      • 1970-01-01
      • 2011-12-20
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      相关资源
      最近更新 更多