如何在字符串列表中搜索关键字并返回该字符串? [英] How to search for a keyword in a list of strings, and return that string?

查看:71
本文介绍了如何在字符串列表中搜索关键字并返回该字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个长度为几个单词的字符串列表,我需要搜索两个关键字,并返回包含这两个关键字的字符串.

I have a list of strings that are a few words long, and I need to search for two keywords, and return the strings that contain those two key words.

我曾尝试遍历字符串,但无法这样做.我尝试了 .find() 函数,但在字符串列表上没有成功.

I have tried to loop through the strings, but was not able to do so. I tried the .find() function but that was not successful on a list of strings.

假设我们有一个列表:

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"的新列表中返回字符串.理想情况下,要获得以下内容:

I would like to iterate through the list of strings and return the strings in a new list that contain both the words "man" and "dog". Ideally, to get the following:

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.

Note : Refrain from assigning variable name as list.

这篇关于如何在字符串列表中搜索关键字并返回该字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆