python:列表索引超出范围错误 [英] python : list index out of range error
问题描述
我已经编写了一个简单的python程序
I have written a simple python program
l=[1,2,3,0,0,1]
for i in range(0,len(l)):
if l[i]==0:
l.pop(i)
这使我在行if l[i]==0:
调试之后,我可以发现i
正在增加,列表正在减少.
但是,我有循环终止条件i < len(l)
.那为什么我会收到这样的错误?
After debugging I could figure out that i
is getting incremented and list is getting reduced.
However, I have loop termination condition i < len(l)
. Then why I am getting such error?
推荐答案
在迭代列表时,您正在减少列表l
的长度,因此当您在range语句中接近索引的末尾时,一些这些索引不再有效.
You are reducing the length of your list l
as you iterate over it, so as you approach the end of your indices in the range statement, some of those indices are no longer valid.
看起来就像您想要做的一样:
It looks like what you want to do is:
l = [x for x in l if x != 0]
,它将返回l
的副本,其中不包含任何零元素(该操作称为列表理解.您甚至可以将最后一部分缩短为if x
,因为非零数字的值为True
.
which will return a copy of l
without any of the elements that were zero (that operation is called a list comprehension, by the way). You could even shorten that last part to just if x
, since non-zero numbers evaluate to True
.
用编写代码的方式,没有像i < len(l)
这样的循环终止条件,因为len(l)
是在循环之前 pre 计算的,不会重新评估在每次迭代中.您可以以这种方式编写它,但是:
There is no such thing as a loop termination condition of i < len(l)
, in the way you've written the code, because len(l)
is precalculated before the loop, not re-evaluated on each iteration. You could write it in such a way, however:
i = 0
while i < len(l):
if l[i] == 0:
l.pop(i)
else:
i += 1
这篇关于python:列表索引超出范围错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!