【发布时间】:2020-08-09 11:13:20
【问题描述】:
为什么会出现这个错误?
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
【问题讨论】:
-
我不明白你不明白什么。假设您的变量“my_list”是一个包含 1 个元素的列表。即使您进行迭代,您的代码也会尝试从 morodata.get('displayattributes') 获取索引为 0-4 的值,而这些值可能不存在。当您的列表只有 1 个元素时,索引为 1 或更多的值不存在。你有适当的例外。如果您想继续这样的配方,请确保 motordata.get('displayAttributes') 中的值始终返回一个包含至少 5 个元素的列表。
-
我建议先声明列表的长度。