“列表索引超出范围” for循环出错

时间:2020-06-27 20:58:14

标签: python loops indexing

免责声明:我对Sage / Python完全没有经验,所以这可能是一个非常简单的错误

我已经定义了一个列表,称为“权重”

weights = [[0,24,16,4,1],[24,0,5,1,6],[16,5,0,15,7],[4,1,15,0,2],[1,6,7,2,0]]

给出特定路径的成本或权重。因此,第一个列表将从第“零”个节点开始,下一个列表将从第一个节点开始,依此类推。

我想创建一个函数getCost,该函数从0 to 4中获取一个整数列表,并将该路径总计的所有开销加起来。

def getCost(list):
    cost = weights[0][list[0]]
    for i in range(1,len(list)+1):
        if list[i] > 4 or list[i] < 0:
            print "Elements in list cannot be greater than 4."
            break
        else:
            cost += weights[list[i-1]][list[i]]
    return "The total cost of this path is " + cost

getCost([1,4,3,2])

但这给了我以下错误信息:

Traceback (most recent call last):
  File "/cocalc/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 1234, in execute
    flags=compile_flags), namespace, locals)
  File "", line 1, in <module>
  File "", line 4, in getCost
IndexError: list index out of range

其中的哪一部分使索引超出范围?我以为,如果我将for循环的范围从i=1开始,就不会遇到下界问题。

2 个答案:

答案 0 :(得分:0)

首先,正如@Swetank Podda所说,list是python中的保留关键字,因此请尝试将list更改为另一个词,例如lslst(只是一个建议)。

然后,您最多迭代i=len(list),超出范围。

请记住,列表的最后一个元素位于索引len(list)-1

lst=[1,2,3,4]
lst[len(lst)] 
>>> IndexError: list index out of range


lst=[1,2,3,4]
lst[len(lst)-1]
>>>4

因此,当您在range(1,len(list)+1)中进行迭代时,会出现索引错误,因为:

#with for i in range(1,len(list)+1):
i=[1,2,3,...,len(list)]

#with for i in range(1,len(list)):
i=[1,2,3,...,len(list)-1]

还要在返回时将成本强制转换为字符串,因为您无法连接str和ints:

return "The total cost of this path is " + cost
>>>TypeError: can only concatenate str (not "int") to str

请尝试:

return "The total cost of this path is " + str(cost)
#or with fstrings
return f"The total cost of this path is {cost}"

因此您的代码已更改:

weights = [[0,24,16,4,1],[24,0,5,1,6],[16,5,0,15,7],[4,1,15,0,2],[1,6,7,2,0]]


def getCost(lst):
    cost = weights[0][lst[0]]
    for i in range(1,len(lst)):
        if lst[i] > 4 or lst[i] < 0:
            print("Elements in list cannot be greater than 4.")
            break
        else:
            cost += weights[lst[i-1]][lst[i]]
    return "The total cost of this path is " + str(cost)

测试:

getCost([1,4,3,2])
>>>The total cost of this path is 47

getCost([1,4,3,7])
>>>Elements in list cannot be greater than 4.
>>>The total cost of this path is 32

答案 1 :(得分:0)

我将首先解释错误的原因,然后在下面提供正确的代码。


错误说明

IndexError: list index out of range

  1. 索引错误:尝试访问超出范围的列表索引时会出现此错误。在您的程序中,您在以下行中从1循环到len(list),包括以下内容-

    for i in range(1,len(list)+1):
    

    索引仅直到len(list)-1为止。请记住,range(a,b)将从ab-1循环。因此,我们希望循环只对1len(list)-1执行。

    为此,我们必须将循环更改为

    for i in range(1,len(list)):       # Will only loop from 1 to len(list)-1. So no IndexError would occur
    

    这只会循环到len(list)-1,并且您的索引不会超出列表的范围。此更改将使您的程序正常工作。

  2. 串联错误:程序中的另一个小错误在线-

    return "The total cost of this path is " + cost
    

    这是行不通的,因为我们不能直接将字符串与int连接。因此,我们将不得不使用str()将cost转换为字符串,然后在连接后返回。如果您在python中知道f字符串,也可以使用它。


更正的代码-

weights = [[0,24,16,4,1],[24,0,5,1,6],[16,5,0,15,7],[4,1,15,0,2],[1,6,7,2,0]]

def getCost(lst):
    cost = weights[0][list[0][0]]
    for i in range(1,len(lst)):         # <-- Loop till range(1,len(list)) only so it doesn't go out of range
        if lst[i] > 4 or lst[i] < 0:
            print "Elements in list cannot be greater than 4."
            break
        else:
            cost += weights[lst[i-1]][lst[i]]
    return "The total cost of this path is " + str(cost)   # <- Note the change here... convert int to str and then concatenate

print(getCost([1,4,3,2]))

输出:

The total cost of this path is 47

注意:

请尽量不要使用list作为变量名称,因为它是python 保留的关键字。我已在上面的代码中将列表更改为lst

希望这会有所帮助!