IndexError:列出索引超出范围-尽管该索引似乎在范围内

时间:2019-08-06 12:05:37

标签: python python-3.x

我刚刚开始自己​​学习编程。我正在研究以下codingbat问题:

返回数组中数字的总和,但忽略以6开头并扩展到下一个7的数字部分(每6个字符后至少跟7个数字)。没有数字则返回0。

def sum67(nums):
    sum = 0
    pos6 = []
    pos7 = []
    for i in range(len(nums)):
        if nums[i] == 6:
            pos6 = pos6 + [i]
    for i in range(pos6[0],len(nums)):
        if nums[i] == 7:
            pos7 = pos7 + [i]
    pos7 = pos7[:len(pos6)]
    start_pos = pos6[0]
    end_pos = pos7[-1]
    for i in range(start_pos,end_pos+1):
        nums[i] = 0
    for i in range(len(nums)):
        sum = sum + nums[i]
    return sum
sum67([2,3,5])
sum67([6,8,3,7,5,9])
sum67([6,7,9,2,1])
sum67([6,7,6,7,7])
sum67([6,7])
sum67([7,8])

运行上面的代码时,出现以下错误。

Traceback (most recent call last):
  File "C:/Users/q1/Google Drive/Python - Practice Examples/test.py", line 26, in <module>
    sum67([2,3,5])
  File "C:/Users/q1/Google Drive/Python - Practice Examples/test.py", line 10, in sum67
    for i in range(pos6[0],len(nums)):
IndexError: list index out of range

当我执行程序时,python向我显示错误:“ IndexError:列表索引超出范围”。我知道此错误的含义,但无法理解为什么在我的情况下会显示该错误?

1 个答案:

答案 0 :(得分:0)

好吧,这是因为如果list由6组成,即pos6将具有值,也就是说,如果nums [i] == 6:实际上位于pos6之内。您应该在此if语句内运行next for循环,因为pos6仅在列表中存在6时才有值,例如:

for i in range(len(nums)):
    if nums[i] == 6:
        pos6 = pos6 + [i]
        for i in range(pos6[0],len(nums)):

希望有帮助。