Sparse assignment list in python

前端 未结 2 1783
我在风中等你
我在风中等你 2020-11-28 15:37

I need a list with the following behavior

>>> l = SparseList()
>>> l
[]
>>> l[2] = \"hello\"
>>> l
[ None, None, \"hello\         


        
2条回答
  •  日久生厌
    2020-11-28 16:19

    Here's minimal code to pass your given examples (with indispensable adjustments: you expect weird spacing and quoting, 'None' to be printed out at the prompt without a print statement, etc etc):

    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)
    

    I imagine you'll want more (to support negative indices, slicing, and whatever else), but this is all your examples are implicitly specifying.

提交回复
热议问题