0

说我有这个清单

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

2 回答 2

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))可能是值得的。

于 2013-03-04T13:34:19.183 回答