IndexError:列出索引超出范围
在本教程中,我们将解决在Python中遇到的 Indexerror: list Index Out of Range
在使用列表时,我们可以通过其索引访问其元素。
当我们尝试访问不存在的索引时,我们将收到此错误。
让我们在举例的帮助下看看。
countryList=["Netherlands","China","Nepal","Bhutan"] print(countryList[3]) print(countryList[4])
输出:
Bhutan
--------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-6-c6cdb4c86747> in <module>
1 countryList=["Netherlands","China","Nepal","Bhutan"]
2 print(countryList[3])
----> 3 print(countryList[4])
IndexError: list index out of range
使用时通常会收到此错误 while或者 for循环在Python中。
让我们了解少数常见场景。
while循环
当我们使用循环时,我们可能会得到 Indexerror: list Index Out of Range。
让我们用榜样来理解:
colorList = ["Orange","Blue","Red","Pink"]
print("colorList length",len(colorList))
i=0
while i <= len(colorList):
print("Index:",i,"Element:", colorList[i])
i+=1
运行上面的程序时,我们将得到以下输出:
4
Index: 0 Element: Orange
Index: 1 Element: Blue
Index: 2 Element: Red
Index: 3 Element: Pink
--------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-9-c07c56d30f4e> in <module>
3 i=0
4 while i <= len(colorList):
----> 5 print("Index:",i,"Element:", colorList[i])
6 i+=1
7
IndexError: list index out of range
你能猜出为什么我们得到 IndexError: list index out of range?
正如我们已经打印了列表的所有元素,我们正在尝试访问 colorList[4],我们正在得到 indexError。
提示:我们在下面发出问题。 while i <= len(colorList):我们应该从0到3迭代,而不是0到4.在Python中,列表索引从0开始,所以我们需要更改 while i <= len(colorList):到 while i < len(colorList):
colorList = ["Orange","Blue","Red","Pink"]
print("colorList length",len(colorList))
i=0
while i < len(colorList):
print("Index:",i,"Element:", colorList[i])
i+=1
运行上面的程序时,我们将得到以下输出:
4索引:0元素:橙色索引:1个元素:蓝色索引:2元素:红色索引:3个元素:粉红色
同样,我们可以获得这个问题 for循环也是如此。
使用索引进行迭代的推荐方法
如果要迭代索引循环,则应使用enumerate()函数。
这是一个例子。
colorList = ["Orange","Blue","Red","Pink"]
for idx, color in enumerate(colorList):
print("Index:",idx,"Element:", color)
正如我们所看到的,我们不必处理 len(colorList)。
在这种情况下,你不会得到 Indexerror: list Index Out of Range
访问元素作为索引
此错误的另一个原因可能是当我们尝试访问元素作为索引时。
让我们在举例的帮助下看看。
listInt = [7,1,5,4,3]
for i in listInt:
print(listInt[i])
输出:
--------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-12-3f8a39f792a8> in <module>
1 listInt = [7,1,5,4,3]
2 for i in listInt:
----> 3 print(listInt[i])
IndexError: list index out of range
如你看到的, i实际上是指元素,我们正在尝试访问index.这就是我们收到此错误的原因。
要解决此问题,我们只需要打印 i而不是 listInt[i]

