python - 为什么我收到 IndexError:列表索引超出范围?
问题描述
为什么我会收到此错误?
motModel = motordata.get('displayAttributes')[1]['value'] or None
IndexError: list index out of range
我正在抓取汽车列表,对于这个特定的列表,列表中只有 1 项。换句话说motordata.get('displayAttributes')[0]
,存在但motordata.get('displayAttributes')[1]
不存在。
我认为i in range(len(my_list))
如果键存在,则使用它会返回一个值,如果不存在,则继续使用下一个键/项目。
my_list = motordata['displayAttributes']
for i in range(len(my_list)):
motMake = motordata.get('displayAttributes')[0]['value'] or None
motModel = motordata.get('displayAttributes')[1]['value'] or None
motYear = motordata.get('displayAttributes')[2]['value'] or None
motMilage = motordata.get('displayAttributes')[3]['value'] or None
motFuel = motordata.get('displayAttributes')[4]['value'] or None
解决方案
这个循环确实没有超出列表的范围:
for i in range(len(my_list)):
在该循环中,您可以i
安全地使用作为索引访问列表元素。但这不是你在做的,你使用的是硬编码的索引值:
motMake = motordata.get('displayAttributes')[0]['value'] or None
motModel = motordata.get('displayAttributes')[1]['value'] or None
motYear = motordata.get('displayAttributes')[2]['value'] or None
motMilage = motordata.get('displayAttributes')[3]['value'] or None
motFuel = motordata.get('displayAttributes')[4]['value'] or None
因此,“对于列表中的每个项目”,您是在告诉代码“给我前 5 个项目”。您明确地告诉代码访问您知道只有一项的列表中的第二项。所以,你得到一个例外。
看起来您根本不想要循环,因为您从未实际使用i
并且总是在循环中覆盖相同的变量。相反,请在访问 5 个硬编码索引值中的每一个之前检查列表的长度。像这样的东西:
my_list = motordata['displayAttributes']
length = len(my_list)
if length > 0:
motMake = motordata.get('displayAttributes')[0]['value']
if length > 1:
motModel = motordata.get('displayAttributes')[1]['value']
if length > 2:
motYear = motordata.get('displayAttributes')[2]['value']
if length > 3:
motMilage = motordata.get('displayAttributes')[3]['value']
if length > 4:
motFuel = motordata.get('displayAttributes')[4]['value']
推荐阅读
- codenameone - 代号 One gui builder 4.32
- scala - 当函数选择列时使用 SparkSQL
- login - 如何在没有端点方法的情况下继续使用 HybridAuth 3
- bash - 使用 sudo 时如何使用 tee
- delphi - 如何在 Delphi 中使用 RTTI 或 TypeInfo 获取枚举的有效范围
- android - 将 Unit Test App Nunit Lite Xamarin 中的引用添加到 Xamarin 服务后重建失败
- php - 关闭浏览器时如何将非常繁重的任务的执行留在队列中(在后台运行)?
- node.js - 如何防止像 SQL 注入这样的 mongo?
- json - 如何迭代层次结构中的 JSON 对象?
- input - Angular6 Material - 使用带有自定义 ErrorStateMatcher 的输入的 Stepper