MaP*_*aPy 6 python list python-2.7
嗨,让我们说我在python中有两个列表,我想从两个列表中删除常用值.潜在的解决方案是:
x = [1, 2, 3, 4, 5, 6, 7, 8]
y = [43, 3123, 543, 76, 879, 32, 14241, 342, 2, 3, 4]
for i in x:
if i in y:
x.remove(i)
y.remove(i)
Run Code Online (Sandbox Code Playgroud)
它似乎是正确的,但事实并非如此.我想,原因是因为从列表中删除了一个项目,索引会继续迭代.因此,对于值彼此接近的列表中的两个常见值,我们将缺少后面的值(代码不会迭代它).结果将是:
>>> x
[1, 3, 5, 6, 8, 9, 10]
>>> y
[43, 3123, 543, 76, 879, 32, 14241, 342, 3]
Run Code Online (Sandbox Code Playgroud)
所以我们错过了价值'3'
.
这种行为的原因是我提到的吗?还是我做错了什么?
只需稍微改变你的代码,迭代x
它的副本x[:]
.你在迭代它时修改列表.这就是为什么你缺少价值3
for i in x[:]:
if i in y:
x.remove(i)
y.remove(i)
Run Code Online (Sandbox Code Playgroud)
和替代方法
x,y = [i for i in x if i not in y],[j for j in y if j not in x]
Run Code Online (Sandbox Code Playgroud)
您还可以使用set
对象的差异.
a = list(set(y) - set(x))
b = list(set(x) - set(y))
Run Code Online (Sandbox Code Playgroud)