从列表中删除常见元素 [英] Removing common elements from lists

查看:83
本文介绍了从列表中删除常见元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有这些列表:

a=[2,6,79,10]
b=[6,7,2,0,8,5]

所需的输出将是:

a=[79,10]
b=[7,0,8,5]

为什么此代码不起作用?

Why is this code not working?

def cel(a,b):
    for x in a:
        if x in b:
            b.remove(x)
            a.remove(x)

推荐答案

您可以为此使用set操作:

you can use set operations for this purpose:

i = set(a).intersection(set(b))
a = list(set(a).difference(i))
b = list(set(b).difference(i))

编辑我尝试调试您的原始代码,并意识到,只要删除一个数字,它就会跳过一个数字.谷歌搜索后,我发现由于某些内部索引问题,在迭代时修改列表不是定义的行为.最简单的解决方法是在您的for循环中使用原始数组的副本:

EDIT I tried to debug your original code and realized that it skips a number whenever it removes one. After googling I found that modifying a list while iterating is not a defined behavior because of some internal indexing issues. The easiest workaround would be using a copy of the original array in your for loop as:

for x in a[:]:
    if x in b:
        b.remove(x)
        a.remove(x)

这篇关于从列表中删除常见元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆