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)