为什么我得到IndexError:列表索引超出范围?

时间:2020-08-09 11:13:20

标签: python scrapy

为什么会出现此错误?

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

2 个答案:

答案 0 :(得分:0)

您能举例说明您正在使用的实际列表或字典吗?

您可能正在尝试调用一个不存在的项目,即当您收到此错误时。

t = ['a','b']

print(t[1])
b

print(t[2])
IndexError: list index out of range

答案 1 :(得分:0)

此循环确实没有超出列表的范围:

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']
相关问题