PYTHON-pop、remove 所犯的逻辑错误

1.remove() 按值删除:

num_list = [1, 2, 2, 2, 3]

for item in num_list:
    if item == 2:
        num_list.remove(item)
        
print(num_list)

num_list = [1, 2, 2, 2, 3]

for item in num_list[:]:
    if item == 2:
        num_list.remove(item)
        
print(num_list)
#结果:
[1, 2, 3]  #留下一个尾巴
[1, 3]      #干干净净

#这个num_list[:] 是产生一个新的列表,我们在新列表遍历,在旧的列表删除。可以看下边
>>> a = [1,2,3,4,5,6]
>>> b = a[:]
>>> a[0] = 1000
>>> b
[1, 2, 3, 4, 5, 6] #改变a后,b不改变
>>> a
[1000, 2, 3, 4, 5, 6]  #但是a变了
>>> 

2.pop():按照下标删除

a = [1,2,3]
b = [4,5,6]
c = list(zip(a,b))

for i in range(len(c)):
    print("本次的长度是:",len(c))
    print("本次的i是:",i)
    c.pop(i)

#原因就在于其i一直增大,而本身i的范围一直减小
本次的长度是: 3
本次的i是: 0
本次的长度是: 2
本次的i是: 1
本次的长度是: 1
本次的i是: 2
Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/pop_ss.py", line 8, in <module>
    c.pop(i)
IndexError: pop index out of range
>>> 

3.参考地址:

https://www.cnblogs.com/34fj/p/6351458.html

https://www.cnblogs.com/xiaodai0/p/10564956.html

https://www.runoob.com/python/att-list-remove.html

原文地址:https://www.cnblogs.com/xiao-yu-/p/12759644.html