【问题标题】:"list index out of range" Error in for loop“列表索引超出范围”for循环中的错误
【发布时间】:2020-06-27 20:58:14
【问题描述】:

免责声明:我完全没有使用 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 开始,我就不会遇到下限问题。

【问题讨论】:

  • 你转到+1,这超出了list[i]的范围
  • list是python中的保留关键字,我建议你使用其他变量名
  • 另外,您可以简单地使用类似以下的内容:for i in your_list 而不是 for i in range(1, len(list)+1)。目前,您将列表的第一个元素分配给cost,这可能违反您指定的条件,因为没有检查。

标签: python loops indexing


【解决方案1】:

我会先解释错误原因,然后在下面给出正确的代码。


错误说明

IndexError: list index out of range

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

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

    索引只到 len(list)-1 。请记住,range(a,b) 将从a 循环到b-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() 将成本转换为字符串,然后在连接后返回。如果您在 python 中知道 f-string,也可以使用它。


更正的代码 -

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 保留的关键字。我已在上面的代码中将 list 更改为 lst

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    首先,正如@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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 2020-07-23
      • 2019-01-07
      • 2020-09-07
      • 1970-01-01
      • 2018-05-19
      相关资源
      最近更新 更多