Python循环:列表索引超出范围 [英] Python Loop: List Index Out of Range
问题描述
提供以下列表
a = [0, 1, 2, 3]
我想创建一个新列表b
,该列表由将a
的当前值和下一个值相加的元素组成.该元素将比a
少 1 个元素.
I'd like to create a new list b
, which consists of elements for which the current and next value of a
are summed. It will contain 1 less element than a
.
赞:
b = [1, 3, 5]
(从0 + 1、1 + 2和2 + 3开始)
(from 0+1, 1+2, and 2+3)
这是我尝试过的:
b = []
for i in a:
b.append(a[i + 1] - a[i])
b
问题是我不断收到此错误:
The trouble is I keep getting this error:
IndexError: list index out of range
我很确定会发生这种情况,因为当我得到(3)的最后一个元素时,我无法将其添加到任何东西中,因为这样做超出了它的值范围(之后没有任何值3添加).因此,我需要告诉代码停止在2处,同时仍要引用3进行计算.
I'm pretty sure it occurs because by the time I get the the last element of a (3), I can't add it to anything because doing so goes outside of the value of it (there is no value after 3 to add). So I need to tell the code to stop at 2 while still referring to 3 for the calculation.
推荐答案
- 在
for
循环中,您正在遍历列表a
的元素.但是在循环的主体中,当您实际需要索引时,您将使用这些项目为该列表建立索引.
想象一下,如果列表a
包含5个项目,则其中将包含100,并且for循环将到达该项目.实际上,您将尝试检索列表a
的第100个元素,该元素显然不存在.这将给您一个IndexError
.
- In your
for
loop, you're iterating through the elements of a lista
. But in the body of the loop, you're using those items to index that list, when you actually want indexes.
Imagine if the lista
would contain 5 items, a number 100 would be among them and the for loop would reach it. You will essentially attempt to retrieve the 100th element of the lista
, which obviously is not there. This will give you anIndexError
.
我们可以通过遍历一系列索引来解决此问题:
We can fix this issue by iterating over a range of indexes instead:
for i in range(len(a))
,然后访问a
的项目,例如:a[i]
.这不会出现任何错误.
and access the a
's items like that: a[i]
. This won't give any errors.
- 在循环的主体中,不仅要索引
a[i]
,而且要索引a[i+1]
.这也是潜在错误的地方.如果您的列表包含5个项目,并且像我在第1点中所示的那样对它进行迭代,则会得到IndexError
.为什么?因为range(5)
本质上是0 1 2 3 4
,所以当循环达到4时,您将尝试获取a[5]
项.由于Python中的索引从0开始且您的列表包含5个项目,因此最后一个项目的索引为4,因此获取a[5]
意味着获取不存在的第六个元素.
- In the loop's body, you're indexing not only
a[i]
, but alsoa[i+1]
. This is also a place for a potential error. If your list contains 5 items and you're iterating over it like I've shown in the point 1, you'll get anIndexError
. Why? Becauserange(5)
is essentially0 1 2 3 4
, so when the loop reaches 4, you will attempt to get thea[5]
item. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting thea[5]
would mean getting the sixth element which does not exist.
要解决此问题,应从len(a)
中减去1以获取范围序列0 1 2 3
.由于您使用的是索引i+1
,因此您仍然会获得最后一个元素,但是这样做可以避免错误.
To fix that, you should subtract 1 from len(a)
in order to get a range sequence 0 1 2 3
. Since you're using an index i+1
, you'll still get the last element, but this way you will avoid the error.
- 有许多不同的方法可以完成您要在此处完成的工作.其中一些非常优雅,更"pythonic",例如列表理解:
b = [a[i] + a[i+1] for i in range(len(a) - 1)]
这只能完成一行工作.
这篇关于Python循环:列表索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!