Reputation: 115
I need to find the difference between two lists using python. This question has been asked many times before on Stack Overflow, but none of them mention duplicates (i.e. the difference between [8]
and [8, 0, 1, 8]
is [0, 1]
; I need it to be [0, 1, 8]
, because the number of each digit is significant in my program).
I've tried using numpy's setdiff1d, but it fails to meet the above criteria
ydiff = np.setdiff1d(ydigits, jdigits)
As mentioned above, this only accounts for whether the same item is in a list, not how many times it is in that list. Is there another function I could use?
Upvotes: 1
Views: 47
Reputation: 107134
You can use the subtraction operator for collections.Counter
objects instead:
>>> from collections import Counter
>>> list((Counter([8, 0, 1, 8]) - Counter([8])).elements())
[8, 0, 1]
Upvotes: 2