如何在字符串列表中搜索关键字,然后返回该字符串?

时间:2019-04-28 18:27:17

标签: python list search 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"]

我想遍历字符串列表,并在包含单词“ man”和“ dog”的新列表中返回字符串。理想情况下,获得以下信息:

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

3 个答案:

答案 0 :(得分:7)

尝试一下:

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

答案 1 :(得分:2)

我会使用正则表达式来避免与 manifold dogma 这样的单词匹配:

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

答案 2 :(得分:0)

尝试一下:

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,因为那样会掩盖内置类型。)