[英]Why do I get an IndexError: list index out of range
In my code I am getting an index error - IndexError: list index out of range.在我的代码中,我收到一个索引错误 - IndexError: list index out of range。 Could you please 1) explain why is this and then 2) make some corrections to my code?
您能否 1)解释为什么会这样,然后 2)对我的代码进行一些更正? Thank you for your answer in advance
感谢您提前回答
x = [1, 2, 3, 4, 5]
for i in range(len(x)):
if x[i] % 2 == 0:
del x[i]
Use a new list (comprehension) instead:改用新列表(理解):
x = [1, 2, 3, 4, 5]
y = [item for item in x if not item % 2 == 0]
print(y)
# [1, 3, 5]
Or - considered "more pythonic":或者 - 被认为是“更pythonic”:
y = [item for item in x if item % 2]
When you use del
you reduce the size of your array but the initial loop goes through the initial size of the array, hence the IndexError.当您使用
del
时,您会减小数组的大小,但初始循环会通过数组的初始大小,因此会出现 IndexError。
If you want to delete items I recommend using list comprehension:如果要删除项目,我建议使用列表理解:
x = [1, 2, 3, 4, 5]
x_filtered = [i for i in x if i%2]
This is because you are removing objects inside of the loop, in other words making the list shorter.这是因为您正在删除循环内的对象,换句话说,使列表更短。
Instead use this:而是使用这个:
x = x[0::2]
To select every second value of the list到 select 列表的每一秒值
If you want all the even vaues, instead use a list generator:如果您想要所有偶数值,请改用列表生成器:
x = [value for value in x in value%2 == 0]
You are deleting items from the very list you are iterating over.您正在从您正在迭代的列表中删除项目。 An alternative approach would be:
另一种方法是:
x = [1, 2, 3, 4, 5]
answer = [i for i in x if i % 2 != 0]
print(answer)
Outputs:输出:
[1, 3, 5]
x = [1, 2, 3, 4, 5]
for i in range(len(x) -1, -1, -1):
if x[i] % 2 == 0:
x.pop(i)
"range function takes three arguments. "范围 function 需要三个 arguments。
First is the start index which is [length of list – 1], that is, the index of last list element(since index of list elements starts from 0 till length – 1).首先是起始索引,即[list of list – 1],即最后一个列表元素的索引(因为列表元素的索引从0开始到length – 1)。
Second argument is the index at which to stop iteration.第二个参数是停止迭代的索引。
Third argument is the step size.第三个参数是步长。 Since we need to decrease index by 1 in every iteration, this should be -1." - Source
因为我们需要在每次迭代中将索引减少 1,所以这应该是 -1。” - 来源
I highly recommend list comprehension however in certain circumstances there is no point and removing through iteration is fine.我强烈推荐列表理解,但是在某些情况下没有意义,通过迭代删除就可以了。 Up to you~
随你~
use while loop instead of for loop if you want to delete some item.如果要删除某些项目,请使用 while 循环而不是 for 循环。
x = [1, 2, 3, 4, 5]
i = 0
while i<len(x):
if x[i]%2==0:
del x[i]
i+=1
print(x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.