alk*_*fas 3 python search list cpu-word
我有一个只有几个单词的字符串列表,我需要搜索两个关键字,然后返回包含这两个关键字的字符串。
我试图遍历字符串,但无法这样做。我尝试了.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"]
Run Code Online (Sandbox Code Playgroud)
我想遍历字符串列表,并在包含单词“ man”和“ dog”的新列表中返回字符串。理想情况下,要获得以下内容:
list_new = ["The man walked the dog", "The man has a brown dog"]
Run Code Online (Sandbox Code Playgroud)
尝试这个 :
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]
Run Code Online (Sandbox Code Playgroud)
输出:
['The man walked the dog', 'The man has a brown dog']
Run Code Online (Sandbox Code Playgroud)
注意:不要将变量名分配为list
。