bug代码:
a = [1, 3, 4, 5, 989, 9]
b = [3, 4]
for i in a:
if i in b:
a.remove(i)
print(a)
预期的输出应该是
[1,5,989,9]
实际输出为:
[1, 4, 5, 989, 9]
原因分析:
python 列表循环的时候改变了列表的本身的值,会导致索引发生变化,错位,最后导致remove失败
解决方案:
from copy import deepcopy
a = [1, 3, 4, 5, 989, 9]
c = deepcopy(a)
b = [3, 4]
for i in c:
if i in b:
a.remove(i)
print(a)
先深拷贝,然后用copy之后的list循环
当然也可以用集合做list相减



