如果您使用 Python,您可能遇到过 IndexError
错误,这是对您编写的某些代码的响应。 Python 中的 IndexError
消息是一个运行时错误。 要理解它是什么以及如何修复它,您必须首先理解什么是索引。 Python 列表(或数组或字典)有一个索引。 项目的索引是它在列表中的位置。 要访问列表中的项目,您可以使用其索引。 例如,考虑一下这个 Python 水果列表
fruits = ["apple", "banana", "orange", "pear", "grapes", "watermelon"]
此列表的范围为 5,因为 Python 中的索引从 0 开始。
- apple: 0 (苹果:0)
- banana: 1 (香蕉:1)
- orange: 2 (橙子:2)
- pear: 3 (梨:3)
- grapes: 4 (葡萄:4)
- watermelon: 5 (西瓜:5)
假设您需要从此列表中打印水果名称 pear
。 您可以使用简单的 print
语句,以及列表名称和要打印的项目的索引
>>> fruits = ["apple", "banana", "orange", "pear", "grapes", "watermelon"]
>>> print(fruits[3])
pear
什么导致 Python 中的 IndexError?
如果您使用的索引号超出列表的范围怎么办? 例如,尝试打印索引号 6(不存在)
>>> fruits = ["apple", "banana", "orange", "pear", "grapes", "watermelon"]
>>> print(fruits[6])
Traceback (most recent call last):
File "", line 2, in
IndexError: list index out of range
正如预期的那样,您会收到 IndexError: list index out of range
作为响应。
如何在 Python 中修复 IndexError
修复 IndexError: list index out of range
错误的唯一解决方案是确保您从列表访问的项目在列表的范围内。 您可以通过使用 range()
和 len()
函数来完成此操作。
range()
函数输出顺序数字,默认从 0 开始,并在指定值之前的数字处停止
>>> n = range(6)
>>> for i in n:
print(i)
0
1
2
3
4
5
5
在列表的上下文中,len()
函数返回列表中的项目数
>>> fruits = ["apple", "banana", "orange", "pear", "grapes", "watermelon"]
>>> print(len(fruits))
6
列表索引超出范围
通过一起使用 range()
和 len()
,您可以防止索引错误。 len()
函数返回列表的长度(在本例中为 6。)将该长度与 range()
一起使用会变成 range(6)
,它返回索引 0、1、2、3、4 和 5 处的项目。
fruits = ["apple", "banana", "orange", "pear", "grapes", "watermelon"]
for i in range(len(fruits)):
print(fruits[i])
apple
banana
orange
pear
grapes
watermelon
修复 Python 循环中的 IndexError
如果不小心,Python 循环中可能会发生索引错误。 考虑以下循环
>>> fruits = ["apple", "banana", "orange", "pear", "grapes", "watermelon"]
>>> n = 0
>>> while n <= len(fruits)
print(fruits[n])
n+=1
apple
banana
orange
pear
grapes
watermelon
Traceback (most recent call last):
File "", line 4, in
IndexError: list index out of range
这个逻辑看起来很合理。 您已将 n
定义为计数器变量,并且您已将循环设置为发生直到它等于列表的长度。 列表的长度为 6,但其范围为 5(因为 Python 从 0 开始其 index
)。 循环的条件是 n <= 6
,因此 while
循环在 n
的值等于 6 时停止
- 当 n 为 0 时 => apple (苹果)
- 当 n 为 1 时 => banana (香蕉)
- 当 n 为 2 时 => orange (橙子)
- 当 n 为 3 时 => pear (梨)
- 当 n 为 4 时 => grapes (葡萄)
- 当 n 为 5 时 => watermelon (西瓜)
- 当 n 为 6 时 => IndexError: list index out of range (IndexError:列表索引超出范围)
当 n
等于 6 时,Python 会产生 IndexError: list index out of range
错误。
解决方案
为了避免 Python 循环中的这个错误,只使用 <(“小于”)运算符,在列表的最后一个索引处停止 while
循环。 这比列表的长度少一个数字
>>> fruits = ["apple", "banana", "orange", "pear", "grapes", "watermelon"]
>>> n = 0
>>> while n < len(fruits)
print(fruits[n])
n+=1
apple
banana
orange
pear
grapes
watermelon
还有另一种修复方法,我也把它留给您去发现。
不再有 Python 索引错误
IndexError
的最终原因是尝试访问数据结构中不存在的项目。 使用 range()
和 len()
函数是一种解决方案,当然要记住 Python 从 0 开始计数,而不是从 1 开始。
1 条评论