如何在字符串列表中搜索关键字,并 return 该字符串?

How to search for a keyword in a list of strings, and return that string?

我有几个字长的字符串列表,我需要搜索两个关键字,return 包含这两个关键字的字符串。

我试过遍历字符串,但没能成功。我尝试了 .find() 函数,但在字符串列表上没有成功。

假设我们有一个列表:

list = ["The man walked the dog", "The lady walked the dog","Dogs 
are cool", "Cats are interesting creatures", "Cats and Dogs was an 
interesting movie", "The man has a brown dog"]

我想遍历字符串列表和 return 新列表中包含单词 "man" 和 "dog" 的字符串。理想情况下,要获得以下内容:

list_new = ["The man walked the dog", "The man has a brown dog"]

试试这个:

list_ = ["The man walked the dog", "The lady walked the dog","Dogs are cool", "Cats are interesting creatures", "Cats and Dogs was an interesting movie", "The man has a brown dog"]
l1 = [k for k in list_ if 'man' in k and 'dog' in k]

输出 :

['The man walked the dog', 'The man has a brown dog']

注意:避免将变量名称分配为 list.

试试这个:

words = ["man", "dog"]
l = ["The man walked the dog", "The lady walked the dog","Dogs are cool", "Cats are interesting creatures", "Cats and Dogs was an interesting movie", "The man has a brown dog"]
new_list = [item for item in l if all((word in item) for word in words)]

给予

['The man walked the dog', 'The man has a brown dog']

(我没有使用名称 list,因为那样会掩盖内置类型。)

我会使用正则表达式来避免匹配 manifolddogma:

这样的词
import re

l = [
    "The man walked the dog", 
    "The lady walked the dog", 
    "Dogs are cool", 
    "Cats are interesting creatures",
    "Cats and Dogs was an interesting movie", 
    "The man has a brown dog",
    "the manner dogma"
]

words = ["man", "dog"]
results = [x for x in l if all(re.search("\b{}\b".format(w), x) for w in words)]
results

>>> ['The man walked the dog', 'The man has a brown dog']