Reputation: 7410
I have 2 lists as follows:
a = ["Ron is great", "Mark is good", "Sheela is bad", "Amy is horrible"]
b = ["Ron", "Mark"]
c = [item for item in a if item in b]
I normally use the above list comprehension to find common elements between 2 lists.However it fails in the above scenario as the IN function does an exact match and hence c is an empty list.How do I circumvent this and try to get a list c which looks like this :
c=["Ron is great", "Mark is good"]
Upvotes: 1
Views: 91
Reputation: 21446
You can try like this,
>>> a = ["Ron is great", "Mark is good", "Sheela is bad", "Amy is horrible"]
>>> b = ["Ron", "Mark"]
>>> [ item for item in a for word in b if word in item]
['Ron is great', 'Mark is good']
>>>
Upvotes: 1
Reputation: 31260
You'll need two loops, for instance
c = [item for item in a
if any(name in item for name in b)]
should be sufficient.
Upvotes: 4
Reputation: 5193
Your problem solved with list expressions
>>> a = ["Ron is great", "Mark is good", "Sheela is bad", "Amy is horrible"]
>>> b = ["Ron", "Mark"]
>>> c= [
... sentence
... for word in b
... for sentence in a
... if word in sentence
... ]
['Ron is great', 'Mark is good']
Upvotes: 2