Panupat
Panupat

Reputation: 462

Searching list using keywords from other list?

Say I have this list

some_list = [
    "red apple",
    "red banana",
    "house is green",
    "blue road",
    "blue hat"
]

I want to specify my keywords in another list.

search_strings = ["red", "green"]

Is there a way to get this end results without too much looping?

# search some_list using keywords from search_strings
red = ["red apple", "red bana"]
green = ["house is green"]

Upvotes: 0

Views: 536

Answers (2)

phipsgabler
phipsgabler

Reputation: 20980

[[words for words in some_list if kw in words.split()] for kw in search_strings]

That gives you:

[['red apple', 'red banana'], ['house is green']]

Also, if the "sencences" in some_list or the length of search_strings get bigger, it might pay to convert them to sets (like search_strings = set(search_strings)).

Upvotes: 1

Related Questions