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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.