Python list set value at index if index does not exist

后端 未结 4 708
感动是毒
感动是毒 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: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']
    

提交回复
热议问题