首页 > 解决方案 > IndexError:列表索引超出范围,使用 for 循环中的索引

问题描述

#Check if each element in input list is at least as big as the one before it.
inputList = [9,10,11,12,13]
flag=0
j = 1
i = 0
for i in range(len(inputList)):
    if inputList[i] < inputList[j] :
        flag=0
    elif inputList[i] > inputList[j] :
        flag=1
    else:
        flag=1
        print("Unexpected Error!!")

    if j < len(inputList):
        j=j+1
    else:
        j=j

if flag == 1 :
    print("Condition Failed")
else:
    print("Condition Passed")

我试图从 for 循环访问我的列表的索引,但它给了我索引错误。

我尝试手动打印索引并且它有效但不是其他方式

Traceback (most recent call last):
  File "prac3.py", line 13, in <module>
    if inputList[i] < inputList[j] :
IndexError: list index out of range

标签: python

解决方案


j总是比 1 大i,所以i最后一个元素的索引何时j超出范围 - 因此出现错误。


推荐阅读