首页 > 解决方案 > 在列表中搜索单词的智能方法

问题描述

我想制作一个能够以智能方式搜索单词列表的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)。

标签: pythonstringlist

解决方案


带过滤器的单衬管:

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

推荐阅读