Python list set value at index if index does not exist

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

提交回复
热议问题