I am trying to match two lists, but I want to pick up the repeat matches too. I can't use set because that would only give me {3} in my second example below.
a = [1,2,3,4]
b = [3,3,4,5]
return [3,4]
a = [1,2,3,3]
b = [3,3,4,5]
return [3,3]
You can use list comprehesion to check and return every item in a if it exists in b like below:
[item for item in a if item in b]
If you want only the elements that are in both a and b (to cover the cases mentioned by @kabanus in the comment), you can use the following:
[item for item in set(a) for i in range(min(a.count(item), b.count(item)))]
Output:
>>> a = [1, 2, 3, 4]
>>> b = [3, 3, 4, 5]
>>> [item for item in set(a) for i in range(min(a.count(item), b.count(item)))]
[3, 4]
>>>
>>> a = [1, 2, 3, 3]
>>> b = [3, 3, 4, 5]
>>> [item for item in set(a) for i in range(min(a.count(item), b.count(item)))]
[3, 3]
>>>
>>> a = [3, 3, 4]
>>> b = [4, 4, 3]
>>> [item for item in set(a) for i in range(min(a.count(item), b.count(item)))]
[3, 4]
Try something like (if order doesn't matter), Python 2:
from collections import Counter
a = [1,2,3,4]
b = [3,3,4,5]
ca=Counter(a)
cb=Counter(b)
print sum([[x]*min(ca[x],cb[x]) for x in set(a)],[])
This should return the list of all repeating matches the number of time they repeat, with no particular ordering beyond grouping together same elements. The output for the above example is:
[3,4]
I'm assuming you missed 4. The other example you have yields what you posted:
[3,3]
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