I have two arrays and I'm trying to find values that are in the first array but not in the second array. However, there is a problem, although there are two b's in the first array, since there is only one b in the other array, it sees that it is the same and gives the output that there is no difference. How can I solve this problem?
x = ["a","b","b"]
y = ["a","b"]
print(set(x)-set(y))
CodePudding user response:
This should solve the issue
for i in y:
if (i in x):
x.remove(i)
print(x)
CodePudding user response:
Try this:
from collections import Counter
res = [k for k, v in (Counter(x) - Counter(y)).items() for _ in range(v)]
The complexity of this approach is the best you can get (i.e., O(n)).
Example:
>>> x = [1,2,2,2,3,4,5]
>>> y = [1,2,4]
>>> res = [k for k, v in (Counter(x) - Counter(y)).items() for _ in range(v)]
>>> res
[2, 2, 3, 5]
You're going to loose the order of your elements with this approach. Let me know if that's not good in your case.
CodePudding user response:
My approach woul be list comprehension:
x = ["a","b","b"]
y = ["a","b"]
[x.remove(element) for element in y if element in x]
Output:
['b']