Populating a list/array by index in Python?

后端 未结 7 1827
一整个雨季
一整个雨季 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:20

    If you don't know the size of the list ahead of time, you could use try/except and then Extend the list in the except:

    L = []
    def add(i, s):
        try:
            L[i] = s
        except IndexError:
            L.extend([None]*(i-len(L)+1))
            L[i] = s
    
    add(12, 'a')
    add(22, 'b')
    

    ----- Update ---------------------------------------------
    Per tgray's comment: If it is likely that your code will throw an Exception most of the time, you should check the length of the List every time, and avoid the Exceptions:

    L = []
    def add(i, s):
        size = len(L)
        if i >= size:
            L.extend([None]*(i-size+1))
            L[i] = s
    

提交回复
热议问题