Populating a list/array by index in Python?

后端 未结 7 1826
一整个雨季
一整个雨季 2021-01-31 17:02

Is this possible:

myList = []

myList[12] = \'a\'
myList[22] = \'b\'
myList[32] = \'c\'
myList[42] = \'d\'

When I try, I get:

#         


        
7条回答
  •  抹茶落季
    2021-01-31 17:22

    For a "sparse list" you could use a dict instead:

    mylist = {}
    mylist[12] = 'a'
    

    etc. If you want an actual list (initialize it with [], not (), of course!-) you need to fill the un-set slots to _some_thing, e.g. None, by a little auxiliary function or by subclassing list.

提交回复
热议问题