在通常编程过程中,经常需要过滤List中的值,比如说:过滤列表中的负数。
现在有一个列表:
data = [-1, 10, -10, -7, -5, 0, -1, -5, -8, 6]
最初想法是:遍历列表并且移除负数,于是就写出如下代码:
for _ in data:
if _ < 0:
data.remove(_)
执行后的data为:
[10, -7, 0, -5, 6]
以上的代码方式无法获取当前数据在List中的真实索引,因此,
换一种方式组织代码:根据列表索引来执行的代码:
for _ in range(0,len(data)-1):
if data[_]<0:
data.pop(_)
执行结果:
-1
-10
-5
-1
-8
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IndexError: list index out of range
>>> data
[10, -7, 0, -5, 6]
可见执行结果完全一致,但是第二种方式报了错。
原因:
List在遍历的过程中,变量_存储的是最初的索引(删除之前的索引),但在遍历过程中,当第一个负数被删除之后,元素的实际索引已经发生变化(之后的元素的索引-1),这会导致被删除的元素后一位上的元素,被遗漏,即没有判断正负而被跳过。
这也是第二种方法导致IndexError的原因。
解决方法:
新建一个List,存储非负数。
代码如下:
data1 = list()
for _ in data:
if _ >= 0:
data1.append(_)
进阶:
data1 = [i for i in data if i>=0]
网友评论