Python 循环:列表索引超出范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37619848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Loop: List Index Out of Range
提问by Dance Party2
Given the following list
鉴于以下列表
a = [0, 1, 2, 3]
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 1less element than a
.
我想创建一个新的 list b
,它由当前和下一个值a
相加的元素组成。它将包含比 少1 个元素a
。
Like this:
像这样:
b = [1, 3, 5]
(from 0+1, 1+2, and 2+3)
(从 0+1、1+2 和 2+3)
Here's what I've tried:
这是我尝试过的:
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
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.
我很确定它会发生,因为当我得到 a (3) 的最后一个元素时,我无法将它添加到任何东西中,因为这样做超出了它的值(在 3 之后没有要添加的值) )。所以我需要告诉代码在 2 处停止,同时仍然参考 3 进行计算。
回答by illright
- 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
.
- 在您的
for
循环中,您正在遍历 list 的元素a
。但是在循环体中,当您真正需要索引时,您正在使用这些项目来索引该列表。
想象一下,如果列表a
将包含 5 个项目,那么其中就有一个数字 100,并且 for 循环会到达它。您实际上将尝试检索 list 的第 100 个元素a
,这显然不存在。这会给你一个IndexError
.
We can fix this issue by iterating over a range of indexes instead:
我们可以通过迭代一系列索引来解决这个问题:
for i in range(len(a))
and access the a
's items like that: a[i]
. This won't give any errors.
并a
像这样访问的项目:a[i]
。这不会给出任何错误。
- 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.
- 在循环体中,您不仅要索引
a[i]
,还要索引a[i+1]
. 这也是一个潜在错误的地方。如果您的列表包含 5 个项目并且您正在迭代它,就像我在第 1 点中显示的那样,您将得到一个IndexError
. 为什么?因为range(5)
本质上是0 1 2 3 4
,所以当循环达到 4 时,您将尝试获取该a[5]
项目。由于 Python 中的索引从 0 开始并且您的列表包含 5 个项目,因此最后一个项目的索引为 4,因此获取 thea[5]
将意味着获取不存在的第六个元素。
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.
要解决这个问题,您应该从中减去 1len(a)
以获得范围序列0 1 2 3
。由于您使用的是 index i+1
,您仍然会得到最后一个元素,但这样您就可以避免错误。
- There are many different ways to accomplish what you're trying to do here. Some of them are quite elegant and more "pythonic", like list comprehensions:
- 有许多不同的方法可以完成您在此处尝试执行的操作。其中一些非常优雅且更“pythonic”,例如列表推导式:
b = [a[i] + a[i+1] for i in range(len(a) - 1)]
b = [a[i] + a[i+1] for i in range(len(a) - 1)]
This does the job in only one line.
这仅在一行中完成工作。
回答by K. Menyah
Try reducing the range of the for loop to range(len(a)-1)
:
尝试将 for 循环的范围缩小到range(len(a)-1)
:
a = [0,1,2,3]
b = []
for i in range(len(a)-1):
b.append(a[i]+a[i+1])
print(b)
This can also be written as a list comprehension:
这也可以写成列表理解:
b = [a[i] + a[i+1] for i in range(len(a)-1)]
print(b)
回答by Everyone_Else
When you call for i in a:
, you are getting the actual elements, not the indexes. When we reach the last element, that is 3
, b.append(a[i+1]-a[i])
looks for a[4]
, doesn't find one and then fails. Instead, try iterating over the indexes while stopping just short of the last one, like
当您调用 时for i in a:
,您获得的是实际元素,而不是索引。当我们到达最后一个元素,那就是3
,b.append(a[i+1]-a[i])
验看a[4]
,没有找到一个,然后失败。相反,尝试迭代索引,同时在最后一个索引之前停止,例如
for i in range(0, len(a)-1): Do something
for i in range(0, len(a)-1): Do something
Your current code won't work yet for the do something part though ;)
不过,您当前的代码还不能用于做某事部分;)
回答by miradulo
You are accessing the list elements and then using them to attempt to index your list. This is not a good idea. You already have an answer showing how you could use indexing to get your sum list, but another option would be to zip
the list with a slice of itself such that you can sum the pairs.
您正在访问列表元素,然后使用它们尝试为您的列表建立索引。这不是一个好主意。您已经有了一个答案,显示了如何使用索引来获取总和列表,但另一种选择是zip
使用自身切片的列表,以便您可以对这些对进行求和。
b = [i + j for i, j in zip(a, a[1:])]