python list删除元素是要注意的坑点

版权声明:本文为博主原创文章,转载需要注明源地址 https://blog.csdn.net/qq_33512078/article/details/79077286

我们直接先给出输出与预期不同的代码

In[28]: a = [1,2,3,4,5,6]
In[29]: for i in a:
   ...:     a.remove(i)
   ...:     
In[30]: a
Out[30]: [2, 4, 6]

在上述for循环中,假设我们删除了index=2的值,原本index=3及之后的值会向前补位,所以在循环中就跳过了原index=3的变量
同理,使用list.pop()函数删除指定元素的时候,也会出现上述情况,如:

In[33]: a = [1,2,3,4,5,6]
In[34]: for index, value in enumerate(a):
   ...:     a.pop(index)
   ...:     
In[35]: a
Out[35]: [2, 4, 6]

如果我们想循环删除列表中的元素,较简单的可用方法有:用一个临时列表保存待删除的元素,在for循环临时列表来删除老列表中的元素;或者直接用剩余元素列表覆盖原列表

猜你喜欢

转载自blog.csdn.net/qq_33512078/article/details/79077286