python - 在列表中搜索单词的智能方法
问题描述
我想制作一个能够以智能方式搜索单词列表的python程序。
假设我有一个这样的列表:
ex_list=["Red Apples", "Green Apples", "Bananas", "Yoghurt", "ApplePie", "Milk", "Pineapple"]
我要搜索的词是:
search_word = "Apple"
我希望程序运行的方式是让它返回“Red Apples”、“Green Apples”、“ApplePie”和“Pineapple”。(因为,它们都包含苹果)
我该如何做到这一点?
我基本上希望它返回具有“a”、“p”、“p”、“l”和“e”的所有内容。我不在乎前面是什么(比如 greenapple)或后面是什么(比如 applePie)。
解决方案
带过滤器的单衬管:
list(filter(lambda x: search_word.lower() in x.lower(), ex_list))
或者使用列表理解:
[x for x in ex_list if search_word.lower() in x.lower()]
ex_list
只需按元素包含的条件过滤您的列表search_word
(不区分大小写)。
结果:
['Red Apples', 'Green Apples', 'ApplePie', 'Pineapple']
推荐阅读
- netflix-metaflow - Metaflow:在浏览器中访问元数据/元流服务 URL 时出现“缺少身份验证令牌”
- r - 在R中使用方括号对数据框进行子集化
- c++ - 高性能计算和线程标识符的保存
- html - 我们如何从头开始以角度创建模态弹出窗口
- mysql - 表截断的 Codeigniter 查询
- reactjs - 我可以打印和变量,但我不能用它设置状态并返回错误未定义
- php - file_get_contents 在 CentOS 7 上不起作用
- javascript - w2ui.Grid 中的自定义标题和组标题
- asp.net-core-webapi - 忽略 .NET core 2.2 WebAPI 中响应对象的任何特定大小写
- intellij-idea - Does the flow plugin work with remote debugging in Intellij?