In Python, How can one subtract two non-unique, unordered lists? Say we have a = [0,1,2,1,0]
and b = [0, 1, 1]
I'd like to do something like c = a - b
and have c
be [2, 0]
or [0, 2]
order doesn't matter to me. This should throw an exception if a does not contain all elements in b.
Note this is different from sets! I'm not interested in finding the difference of the sets of elements in a and b, I'm interested in the difference between the actual collections of elements in a and b.
I can do this with a for loop, looking up the first element of b in a and then removing the element from b and from a, etc. But this doesn't appeal to me, it would be very inefficient (order of O(n^2)
time) while it should be no problem to do this in O(n log n)
time.
subtract two lists using Zip() Function In this method, we'll pass the two input lists to the Zip Function. Then, iterate over the zip object using for loop. On every iteration, the program will take an element from list1 and list2, subtract them and append the result into another list.
subtract() in Python. numpy. subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise.
I know "for" is not what you want, but it's simple and clear:
for x in b: a.remove(x)
Or if members of b
might not be in a
then use:
for x in b: if x in a: a.remove(x)
I would do it in an easier way:
a_b = [e for e in a if not e in b ]
..as wich wrote, this is wrong - it works only if the items are unique in the lists. And if they are, it's better to use
a_b = list(set(a) - set(b))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With