Python错误

Hic*_*ick 2 python

a=[]
a.append(3)
a.append(7)

for j in range(2,23480):
    a[j]=a[j-2]+(j+2)*(j+3)/2
Run Code Online (Sandbox Code Playgroud)

当我编写此代码时,它会出现如下错误:

Traceback (most recent call last):
  File "C:/Python26/tcount2.py", line 6, in <module>
    a[j]=a[j-2]+(j+2)*(j+3)/2
IndexError: list assignment index out of range
Run Code Online (Sandbox Code Playgroud)

我可以知道为什么以及如何调试它?

hao*_*hao 7

更改此行代码:

a[j]=a[j-2]+(j+2)*(j+3)/2
Run Code Online (Sandbox Code Playgroud)

对此:

a.append(a[j-2] + (j+2)*(j+3)/2)
Run Code Online (Sandbox Code Playgroud)


Ste*_*202 6

您正在添加新元素,即尚不存在的元素.因此,您需要使用append:由于项目尚不存在,因此您无法通过索引引用它们.可变序列类型的操作概述.

for j in range(2, 23480):
    a.append(a[j - 2] + (j + 2) * (j + 3) / 2)
Run Code Online (Sandbox Code Playgroud)