Reputation: 640
I have a list of strings that are a few words long, and I need to search for two keywords, and return the strings that contain those two key words.
I have tried to loop through the strings, but was not able to do so. I tried the .find() function but that was not successful on a list of strings.
Lets say we have a list:
list = ["The man walked the dog", "The lady walked the dog","Dogs
are cool", "Cats are interesting creatures", "Cats and Dogs was an
interesting movie", "The man has a brown dog"]
I would like to iterate through the list of strings and return the strings in a new list that contain both the words "man" and "dog". Ideally, to get the following:
list_new = ["The man walked the dog", "The man has a brown dog"]
Upvotes: 3
Views: 12025
Reputation: 1858
I would use a regex to avoid matchings with words like manifold or dogma:
import re
l = [
"The man walked the dog",
"The lady walked the dog",
"Dogs are cool",
"Cats are interesting creatures",
"Cats and Dogs was an interesting movie",
"The man has a brown dog",
"the manner dogma"
]
words = ["man", "dog"]
results = [x for x in l if all(re.search("\\b{}\\b".format(w), x) for w in words)]
results
>>> ['The man walked the dog', 'The man has a brown dog']
Upvotes: 2
Reputation: 2764
Try this:
words = ["man", "dog"]
l = ["The man walked the dog", "The lady walked the dog","Dogs are cool", "Cats are interesting creatures", "Cats and Dogs was an interesting movie", "The man has a brown dog"]
new_list = [item for item in l if all((word in item) for word in words)]
gives
['The man walked the dog', 'The man has a brown dog']
(I didn't use the name list
since that would mask the built-in type.)
Upvotes: 1
Reputation: 6920
Try this :
list_ = ["The man walked the dog", "The lady walked the dog","Dogs are cool", "Cats are interesting creatures", "Cats and Dogs was an interesting movie", "The man has a brown dog"]
l1 = [k for k in list_ if 'man' in k and 'dog' in k]
OUTPUT :
['The man walked the dog', 'The man has a brown dog']
Note : Refrain from assigning variable name as list
.
Upvotes: 9