在Python中自动增长列表

Ano*_*ous 14 python list

有没有办法在Python中创建一个自动增长的列表?我的意思是制作一个列表,当引用一个尚不存在的索引时,该列表会增长.基本上是Ruby数组的行为.

提前致谢!

dan*_*rth 38

当然有可能,你只需要使用列表的子类来完成它.

class GrowingList(list):
    def __setitem__(self, index, value):
        if index >= len(self):
            self.extend([None]*(index + 1 - len(self)))
        list.__setitem__(self, index, value)
Run Code Online (Sandbox Code Playgroud)

用法:

>>> grow = GrowingList()
>>> grow[10] = 4
>>> len(grow)
11
>>> grow
[None, None, None, None, None, None, None, None, None, None, 4]
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这对密集数组非常有用,如果您需要稀疏数组的结构,那么最好使用基于字典的解决方案. (5认同)
  • 我不认为将参数(甚至是默认参数)添加到特殊函数是好python,如果规范更改并添加另一个参数该怎么办.我想如果你需要一个fillvalue然后你应该把它添加到`__init__`函数,但是从list继承后不能很好,你需要改变`__new__`方法,但我只是在尝试写一个简单的例子. (3认同)