0

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"]

2 Answers 2

2

Some of the answers in the following questions can be adapted to your purpose:
python: Searching strings in one list in another list then appending an entire list entry to a new list,
Search for any word or combination of words from one string in a list (python),
How to search string members of a list in another string in Python 2,
Remove list entries that match any entry in another list,
Search a list of strings for any sub-string from another list,
Python: search for strings listed in one file from another text file?,
If string does not contain any of list of strings in python
The answers to those questions include various loop or list comprehension techniques (like in phg's answer to the current question) and also include filter illustrations you may find useful.

1
[[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)).

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.