Reputation: 120
I need to compare list_a against many others. my problem starts when there's a duplicated item in the other lists (two k's in other_b).
my goal is to filter out all the lists with the same items (up to three matching items).
list_a = ['j','k','a','7']
other_b = ['k', 'j', 'k', 'q']
other_c = ['k','k','9','k']
>>>filter(lambda x: not x in list_a,other_b)
['q']
I need a way that would return ['k', 'q'], because 'k' appears only once in list_a.
comparing list_a and other_c with set() isn't good for my purpose since it will return only one element: k. while I need ['k','9','k']
I hope I was clear enough.
Thank you
Upvotes: 1
Views: 1347
Reputation: 16403
The following function returns the new list that you want, when giving list_a
as the first argument and other_b
as the second:
def my_comp(my_list, other_list):
other_cop = other_list[:]
for x in my_list:
try:
other_cop.remove(x)
except ValueError:
pass
return other_cop
It copys the other_list
and removes every elemnt from my_list
from the copy. Because if the element to remove is not in other_list
, remove
raises a ValueError
that we have to catch and do nothing on this exception.
Upvotes: 1