python - 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
解决方案
j
总是比 1 大i
,所以i
最后一个元素的索引何时j
超出范围 - 因此出现错误。
推荐阅读
- algorithm - 为什么在 Edmonds Karp 算法中使用 BFS 以使其与 Ford Fulkerson 更好?
- postgresql - Crystal Reports SQL 命令的 Postgresql 参数化查询
- hyperledger-fabric - Hyperledger Fabric:为什么 cryptogen 不生成所有必要的加密材料来注册新用户?
- python - 为什么 __dict__ 不包含类成员,除非使用正确的初始化?
- r - rlang::fn_fmls() 可以嵌套吗?
- datatables - 数据表:缺少页面元素(排序、搜索、下一个...)
- php - 为什么 Laravel 找不到使用“/”的控制器?
- google-app-engine - kubectl 命令找不到命名空间值
- node.js - 如何使用 mongoose 创建和更新参考文档?
- android - Val cannot be reassigned 错误,即使我已经将其更改为 Var Kotlin