当前位置: 动力学知识库 > 问答 > 编程问答 >

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. How do I handle the case where there are no same values?

网友答案:

Using set intersection to detect the common elements:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: