python for循环里面使用remove的坑

博客讨论了在Python中遍历列表并删除元素时遇到的问题。原始代码在遍历过程中删除元素导致未遍历完整个列表。解决方案是先将要删除的元素存储在另一个列表中,然后批量删除。更新后的代码成功地遍历并删除了所有符合条件的元素。
摘要由CSDN通过智能技术生成
K = 3
A = 2
choices = [i for i in range(-1, K)]
list_K_G = np.array([[0, 1, 2], [0, 2, 2]])
print("list_K_G:\n{:}".format(list_K_G))

print("---删除已经达到A的选择---")
print("删除前 choices:{:}".format(choices))
for l in choices:
    print("l:{:}".format(l))
    print("list_K_G[1][{:}]:{:}".format(l, list_K_G[1][l]))
    if(l != -1 and list_K_G[1][l] == A):
        choices.remove(l)
print("删除后 choices:{:}".format(choices))
print("---删除已经达到A的选择---")
输出:
list_K_G:
[[0 1 2]
 [0 2 2]]
---删除已经达到A的选择---
删除前 choices:[-1, 0, 1, 2]
l:-1
list_K_G[1][-1]:2
l:0
list_K_G[1][0]:0
l:1
list_K_G[1][1]:2
删除后 choices:[-1, 0, 2]
---删除已经达到A的选择---

为什么不会遍历l=2呢?因为remove之后索引会加1,原来[-1,0,1,2]中1的索引位置是2,删除以后变成了[-1,0,2],此时索引位置是2的值变成了2,for循环以为索引位置2已经遍历过了。

于是我只能把查找到的需要删除的元素加入一个列表,再根据这个列表删除元素。

K = 3
A = 2
choices = [i for i in range(-1, K)]
list_K_G = np.array([[0, 1, 2], [0, 2, 2]])
print("list_K_G:\n{:}".format(list_K_G))

delete_array = []
print("---删除已经达到A的选择---")
print("删除前 choices:{:}".format(choices))
for l in choices:
    print("l:{:}".format(l))
    print("list_K_G[1][{:}]:{:}".format(l, list_K_G[1][l]))
    if(l != -1 and list_K_G[1][l] == A):
        delete_array.append(l)

for i in delete_array:
    choices.remove(i)
print("删除后 choices:{:}".format(choices))
print("---删除已经达到A的选择---")
输出:
list_K_G:
[[0 1 2]
 [0 2 2]]
---删除已经达到A的选择---
删除前 choices:[-1, 0, 1, 2]
l:-1
list_K_G[1][-1]:2
l:0
list_K_G[1][0]:0
l:1
list_K_G[1][1]:2
l:2
list_K_G[1][2]:2
删除后 choices:[-1, 0]
---删除已经达到A的选择---

参考资料:https://www.cnblogs.com/xiaofeng91/p/11968089.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值