python:迭代弹出元素时列出索引超出范围错误 [英] python : list index out of range error while iteratively popping elements

查看:35
本文介绍了python:迭代弹出元素时列出索引超出范围错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个简单的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)

如果l [i] == 0:

This gives me error 'list index out of range' on line 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 的长度,因此当您在索引中接近索引的末尾时范围语句,其中一些索引不再有效.

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 的副本,其中没有任何为零的元素(该操作称为

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆