IndexError:列表索引超出while循环范围

时间:2018-06-02 13:55:15

标签: python list loops indexing

我无法理解为什么我会得到索引错误。

a = array1[item]

    while item <= n:
        a = array1[item]
        t = mid - a
        l = h_f(t)
        ab += l
        if ab > k:
            item+=1
            break
        ae += h_f(t + 1) - 1
        item+=1

n - 输入值的数量,item = 0

array1 = [2, 3, 4]

任何帮助?

2 个答案:

答案 0 :(得分:0)

包含n元素的列表包含索引0n-1中的项目。即,你的循环应该在n之前停止,而不是在它之前。将<=替换为<,您应该没问题:

while item < n:
   # Here -^

答案 1 :(得分:0)

数组从0开始索引,因此最后一个索引为2。 虽然n可以是3个代码可以超出范围

while item < n:
相关问题