Populating a list/array by index in Python?

后端 未结 7 1828
一整个雨季
一整个雨季 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 17:36

    You'll have to pre-fill it with something (e.g. 0 or None) before you can index it:

    myList = [None] * 100  # Create list of 100 'None's
    myList[12] = 'a'  # etc.
    

    Alternatively, use a dict instead of a list, as Alex Martelli suggested.

提交回复
热议问题