Python list set value at index if index does not exist

后端 未结 4 694
感动是毒
感动是毒 2020-12-11 01:47

Is there a way, lib, or something in python that I can set value in list at an index that does not exist? Something like runtime index creation at list:

l =          


        
相关标签:
4条回答
  • 2020-12-11 02:13

    If you really want the syntax in your question, defaultdict is probably the best way to get it:

    from collections import defaultdict
    def rec_dd(): 
        return defaultdict(rec_dd)
    
    l = rec_dd()
    l[3] = 'foo'
    
    print l
    {3: 'foo'}
    
    l = rec_dd()
    l[0][2] = 'xx'
    l[1][0] = 'yy'
    print l
    <long output because of defaultdict, but essentially)
    {0: {2: 'xx'}, 1: {0: 'yy'}}
    

    It isn't exactly a 'list of lists' but it works more or less like one.

    You really need to specify the use case though... the above has some advantages (you can access indices without checking whether they exist first), and some disadvantages - for example, l[2] in a normal dict will return a KeyError, but in defaultdict it just creates a blank defaultdict, adds it, and then returns it.

    Other possible implementations to support different syntactic sugars could involve custom classes etc, and will have other tradeoffs.

    0 讨论(0)
  • 2020-12-11 02:17

    There isn't a built-in, but it's easy enough to implement:

    class FillList(list):
        def __setitem__(self, index, value):
            try:
                super().__setitem__(index, value)
            except IndexError:
                for _ in range(index-len(self)+1):
                    self.append(None)
                super().__setitem__(index, value)
    

    Or, if you need to change existing vanilla lists:

    def set_list(l, i, v):
          try:
              l[i] = v
          except IndexError:
              for _ in range(i-len(l)+1):
                  l.append(None)
              l[i] = v
    
    0 讨论(0)
  • 2020-12-11 02:20

    Not foolproof, but it seems like the easiest way to do this is to initialize a list much larger than you will need, i.e.

    l = [None for i in some_large_number]
    l[3] = 'foo'
    # [None, None, None, 'foo', None, None None ... ]
    
    0 讨论(0)
  • 2020-12-11 02:26

    You cannot create a list with gaps. You could use a dict or this quick little guy:

    def set_list(i,v):
        l = []
        x = 0
        while x < i:
            l.append(None)
            x += 1
        l.append(v)
        return l
    
    print set_list(3, 'foo')
    >>> [None, None, None, 'foo']
    
    0 讨论(0)
提交回复
热议问题