Why does this iterative list-growing code give IndexError: list assignment index out of range?

后端 未结 9 1833
慢半拍i
慢半拍i 2020-11-22 07:34

Please consider the following code:

i = [1, 2, 3, 5, 8, 13]
j = []
k = 0

for l in i:
    j[k] = l
    k += 1

print j

The output (Python 2

相关标签:
9条回答
  • 2020-11-22 08:17

    I think the Python method insert is what you're looking for:

    Inserts element x at position i. list.insert(i,x)

    array = [1,2,3,4,5]
    
    array.insert(1,20)
    
    print(array)
    
    # prints [1,2,20,3,4,5]
    
    0 讨论(0)
  • 2020-11-22 08:17

    One more way:

    j=i[0]
    for k in range(1,len(i)):
        j = numpy.vstack([j,i[k]])
    

    In this case j will be a numpy array

    0 讨论(0)
  • 2020-11-22 08:18

    You could use a dictionary (similar to an associative array) for j

    i = [1, 2, 3, 5, 8, 13]
    j = {} #initiate as dictionary
    k = 0
    
    for l in i:
        j[k] = l
        k += 1
    
    print j
    

    will print :

    {0: 1, 1: 2, 2: 3, 3: 5, 4: 8, 5: 13}
    
    0 讨论(0)
提交回复
热议问题