在Python中自动增长列表
发布于 2021-01-29 18:37:41
有没有办法在Python中建立一个自动增长的列表?我的意思是制作一个列表,该列表将在引用不存在的索引时增长。基本上是Ruby数组的行为。
提前致谢!
关注者
0
被浏览
50
1 个回答
-
当然有可能,您只需要使用list的子类即可。
class GrowingList(list): def __setitem__(self, index, value): if index >= len(self): self.extend([None]*(index + 1 - len(self))) list.__setitem__(self, index, value)
用法:
>>> grow = GrowingList() >>> grow[10] = 4 >>> len(grow) 11 >>> grow [None, None, None, None, None, None, None, None, None, None, 4]