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
You can try something like this:
class mylist(list):
def __sub__(self, b):
result = self[:]
b = b[:]
while b:
try:
result.remove(b.pop())
except ValueError:
raise Exception("Not all elements found during subtraction")
return result
a = mylist([0, 1, 2, 1, 0] )
b = mylist([0, 1, 1])
>>> a - b
[2, 0]
You have to define what [1, 2, 3] - [5, 6] should output though, I guess you want [1, 2, 3] thats why I ignore the ValueError.
Edit:
Now I see you wanted an exception if a
does not contain all elements, added it instead of passing the ValueError.