Skip to main content
 首页 » 编程设计

python之如何检查列表中的单词是否至少包含一定数量的单个字母

2025年05月04日10itcoder

在 Python 中,我想知道一个列表是否包含一个项目以及有多少。

例如,在:

sentence = "Paul sat in a tree and watched seven squirrels playing on the ground."  

我希望能够只提取包含两个 e 的单词,打印出来

["tree", "seven"]. 

目前我有:

[x for x in sentence.split() if "ee" in x] 

但这只会输出 ["Tree"] 因为我假设它只能挑选出两个 e 直接相邻的单词。

我该怎么做才能覆盖元素中的所有 e,而不管它们位于何处?

请您参考如下方法:

您可以使用 count获取字符串中元素的个数

In [1]: data = "Paul sat in a tree and watched seven squirrels playing on the ground." 
 
In [2]: [x for x in data.split() if x.count('e') > 1] 
Out[2]: ['tree', 'seven']