简体   繁体   English

从python中的两个列表中删除相同的元素

[英]Removing an element that is same from both lists in python

I am writing a function to delete an element which is the same in both lists.我正在编写一个函数来删除两个列表中相同的元素。

 def del_same_elements(num1,num2):
        for i in range(0,len(num1)):
            for j in range(0,len(num2)):

                if num1[i] == num2[j]:
                    same = num1[i]

        num1.remove(same)
        num2.remove(same)

        return num1,num2

Calling print (del_same_elements([3,11],[2,2,3])) returns [11],[2,2] as expected, but when trying print (del_same_elements([3],[2,2])) I get the error local variable 'same' referenced before assignment .调用print (del_same_elements([3,11],[2,2,3]))按预期返回[11],[2,2] ,但在尝试print (del_same_elements([3],[2,2]))local variable 'same' referenced before assignment收到错误local variable 'same' referenced before assignment How do I handle the case where there are no same values?我如何处理没有相同值的情况?

Using set intersection to detect the common elements:使用集合intersection来检测公共元素:

def rm_same(num1, num2):
    same = set(num1).intersection(num2)
    for s in same:
        num1.remove(s)
        num2.remove(s)
    return num1, num2

Use a bit of set theory and calculate the intersection of the list and then remove the items intersection使用一些集合论并计算列表的交集,然后删除项目交集

def del_same_elements(num1, num2):
    same = list(set(num1) & set(num2))

    for i in same:
        num1.remove(i)
        num2.remove(i)

    return num1, num2

if __name__ == "__main__":
    num1, num2 = del_same_elements([1,2,3,4,5], [1,3,5,6])

print num1
print num2

the result结果

[2, 4]
[6]

This also worked perfectly where there is not interseciton since nothing will be removed这在没有交叉的地方也很有效,因为什么都不会被删除

Alternatively, you could have written program like this或者,您可以编写这样的程序

def del_same_elements(num1,num2):
    for num in num1 + num2:
        if num in num1 and num in num2:
            num1.remove(num)
            num2.remove(num)

    return num1, num2

print (del_same_elements([3,11],[2,2, 3]))

This can be a better solution.这可能是一个更好的解决方案。

OR, you could use sets instead:或者,您可以改用集合:

same = set(num1) & set(num2)

while same:
    val = same.pop()
    num1.remove(val)
    num2.remove(val)

Which at least avoids those nested loops.这至少避免了那些嵌套循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM