Skip to main content
 首页 » 编程设计

python之IndexError : list index out of range. 为什么我在第二个函数中出现此错误,但在第一个函数中却没有

2024年10月17日6daizhj

derivative 函数计算多项式的导数;每个条目的度数需要减一,每个条目必须乘以前一个度数,并且需要删除 degree[0] 处的项。

这段代码

lst = [1,2,3] """This list represents the polynomial 3x^2+2x+1""" 
 
"""This function moves each entry one index down and removes the last  
entry""" 
 
def move(lst): 
    copy = list(lst) 
    for i in range(len(lst)): 
        lst[i-1] = copy[i] 
    del lst[-1] 
    print lst 
 
move(lst) 

产生这个:

Samuels-MacBook:python barnicle$ python problemset2.py 
[2, 3] 

这段代码:

def derivative(poly): 
    copy = list(poly) 
    degree = 0 
    for i in range(len(poly)): 
        i = degree*(i+1)  
        poly[i-1] = copy[i] 
        degree += 1 
    del poly[-1] 
    print poly 
 
derivative(lst) 

产生这个错误:

Samuels-MacBook:python barnicle$ python problemset2.py 
 
     Traceback (most recent call last):   File "problemset2.py", line 59, 
     in <module> 
         derivative(lst)   File "problemset2.py", line 55, in derivative 
         poly[i-1] = copy[i] IndexError: list index out of range 

所以,我想通了。这是我的新功能,已重命名为 ddx2:

lst = [0,3,5,4] #lst represents the polynomial 4x^3+3x^2+5x 
def ddx2(lst): 
    for i in range(len(lst)): 
        lst[i] = lst[i]*i 
        if i != 0: 
            lst[i-1] = lst[i] 
    del lst[-1] 
    print lst 
ddx2(lst) #Here I call the function 

当我调用该函数时,我得到了正确格式的正确导数,即 [3,10,12]。我认为我收到的错误消息是因为我在退出循环之前试图缩短列表的长度。

请您参考如下方法:

i = degree*(i+1) 行基本上表示平方指数。您有长度为 i 的数组,但试图获取索引为 i*i 的元素。