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
我很确定它会发生,因为当我获得 a (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)]
这仅在一行中完成工作.
This does the job in only one line.
这篇关于Python 循环:列表索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!