错误的代码
x = ['a', 'b', 'c', 'd'] y = ['b', 'c'] for i in x: if i in y: x.remove(i) print x ----------------- ['a', 'c', 'd']
|
正确的代码
x = ['a', 'b', 'c', 'd'] y = ['b', 'c'] for i in x[:]: if i in y: x.remove(i) print x ----------------- ['a', 'd']
|
实际上,id(x)
与id(x[:])
是不同的,所以只有在x
的副本(x[:]
)中遍历,然后在x
中删除,才不会造成错误。
近期评论