栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python for循环里面使用remove的坑

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python for循环里面使用remove的坑

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/726232.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号