Python list set value at index if index does not exist

后端 未结 4 695
感动是毒
感动是毒 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
    

    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.

提交回复
热议问题