使用其他列表中的关键字搜索列表?

时间:2013-03-04 13:28:17

标签: python python-2.7

说我有这个清单

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

2 个答案:

答案 0 :(得分:2)

答案 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))。