【问题标题】:Why am I getting IndexError: list index out of range? [closed]为什么我收到 IndexError:列表索引超出范围? [关闭]
【发布时间】: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 个元素的列表。
  • 我建议先声明列表的长度。

标签: python scrapy


【解决方案1】:

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

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']

【讨论】:

    猜你喜欢
    • 2011-11-30
    • 2021-02-08
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 2011-10-31
    • 2015-06-26
    相关资源
    最近更新 更多