Reputation: 437
I realize versions of this have been asked before, but I can't find exactly what I'm looking for. I have two lists. I want to only print the items from otherList that do not contain items from firstList.
firstList = ["ABC", "DEF"]
otherList = ["ABCfoo", "foobar", "DEFfoo", "otherFooBar"]
matching = [s for s in otherList if "ABC" not in s] #Not sure how to apply this to multiple strings in a list
Desired result:
["foobar", "otherFooBar"]
Upvotes: 2
Views: 528
Reputation: 38415
You can use regex,
import re
pattern = '|'.join(firstList)
matching = [word for word in otherList if not re.search(pattern, word) ]
['foobar', 'otherFooBar']
Upvotes: 1
Reputation: 21
make a copy and remove elements
>>> matching = otherList.copy()
>>> for a in firstList:
... for b in matching:
... if a in b:
... matching.remove(b)
...
>>> matching
['foobar', 'otherFooBar']
Upvotes: 2
Reputation: 54213
matching = [el for el in otherList if not any(substr in el for substr in firstList)]
You could write not any(substr in el ...)
as all(substr not in el ...)
if that makes more sense to you.
Upvotes: 4