Python List - “reserving” space ( ~ resizing)

后端 未结 4 1249
既然无缘
既然无缘 2021-01-03 22:42

I am given a list l and I want to do assignment:

l[index] = val

But there might be a case when the list is too small.

4条回答
  •  爱一瞬间的悲伤
    2021-01-03 23:34

    Perhaps this does what you want:

    def resize(l, newsize, filling=None):                                                                                  
        if newsize > len(l):                                                                                 
            l.extend([filling for x in xrange(len(l), newsize)])                                                 
        else:                                                                                                
            del l[newsize:]                  
    

提交回复
热议问题