python中的稀疏分配列表

发布于 2021-01-29 19:14:47

我需要具有以下行为的列表

>>> l = SparseList()
>>> l
[]
>>> l[2] = "hello"
>>> l
[ None, None, "hello"]
>>> l[5]
None
>>> l[4] = 22
>>> l
[ None, None, "hello", None, 22]
>>> len(l)
5
>>> for i in l: print i
None
None
"hello"
None
22

尽管它可以通过字典“模拟”,但并不完全相同。numpy数组可以以这种方式运行,但是我不想为这样的事情导入整个numpy。在自己编写代码之前,请问标准库中是否存在类似的内容。

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

    以下是传递给定示例的最少代码(进行必要的调整:您期望使用怪异的空格和引号,在没有print声明的情况下在提示符下显示“无”等):

    class SparseList(list):
      def __setitem__(self, index, value):
        missing = index - len(self) + 1
        if missing > 0:
          self.extend([None] * missing)
        list.__setitem__(self, index, value)
      def __getitem__(self, index):
        try: return list.__getitem__(self, index)
        except IndexError: return None
    
    __test__ = dict(allem='''
    >>> l = SparseList()
    >>> l
    []
    >>> l[2] = "hello"
    >>> l
    [None, None, 'hello']
    >>> print l[5]
    None
    >>> l[4] = 22
    >>> l
    [None, None, 'hello', None, 22]
    >>> len(l)
    5
    >>> for i in l: print i
    None
    None
    hello
    None
    22
    ''')
    import doctest
    doctest.testmod(verbose=1)
    

    我想您会想要更多(支持负索引,切片等),但这是您所有示例的隐式指定。



知识点
面圈网VIP题库

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

去下载看看