说我有这个清单
some_list = [
"red apple",
"red banana",
"house is green",
"blue road",
"blue hat"
]
我想在另一个列表中指定我的关键字。
search_strings = ["red", "green"]
有没有办法在没有太多循环的情况下获得最终结果?
# search some_list using keywords from search_strings
red = ["red apple", "red bana"]
green = ["house is green"]
答案 0 :(得分:2)
以下问题中的一些答案可以根据您的目的进行调整:
•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
这些问题的答案包括各种循环或列表理解技巧(如phg对当前问题的回答),还包括您可能觉得有用的filter
插图。
答案 1 :(得分:1)
[[words for words in some_list if kw in words.split()] for kw in search_strings]
这会给你:
[['red apple', 'red banana'], ['house is green']]
此外,如果some_list
中的“句子”或search_strings
的长度变得更大,则可能需要将它们转换为集合(例如search_strings = set(search_strings)
)。