在Python中自动增长列表

发布于 2021-01-29 18:37:41

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

提前致谢!

关注者
0
被浏览
50
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    当然有可能,您只需要使用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]
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看