索引器错误:列表索引超出范围。为什么我在第二个函数中得到这个错误而不是在第一个函数中?

2024-09-27 07:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

函数导数计算多项式的导数;每个项的阶数需要减少1,每个项必须乘以上一个阶数,阶数[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]。我想我收到的错误信息是因为我试图在退出循环之前缩短列表的长度。你知道吗


Tags: theinpyforlendefrangelist
3条回答

索引i及其计算i = degree*(i+1)将增长等于或大于len(poly)len(copy),因此超出范围

这里是一个快速的黑客我做:)希望它能满足您的要求,你只是要知道名单的长度。你知道吗

lst = [1,2,3] 


dlist=[]
derivate=[]
for i in range(len(lst)): #Here you multiply the coeficients by the power
    dlist.append(lst.__getitem__(i)*i)
#print dlist
for m in range(len(dlist)): #In the derivate the constants become zero
    if dlist.__getitem__(m) != 0:
        derivate.append(dlist.__getitem__(m))
print lst
print derivate

好好享受!你知道吗

线i = degree*(i+1)基本上是指平方指数。您有一个长度为i的数组,但试图获取索引为i*i的元素。你知道吗

相关问题 更多 >

    热门问题