Skip to main content
 首页 » 编程设计

python之计算列表中字母表的出现次数

2025年05月04日15powertoolsteam

我正在用 python 编写代码,使用列表理解来计算字母表在给定序列中出现的次数

例如:

countoccur("s", "ssssdfrtsgjdt" )  

应该给出 5 作为输出,因为 s 出现了五次。我编写了这段代码并得到了以下输出:

def countoccur(x,s): 
    y=[e for e in s if e==x] 
    return y 

输出:

['s', 's', 's', 's', 's'] 

有人可以帮我解决这个问题吗?

请您参考如下方法:

Python 有更好的工具,但如果你想保留你的代码,只需返回 y 的 len:

def countoccur(x,s): 
    y=[e for e in s if e==x] 
    return len(y) 

输出:

output: 5 

您还可以使用 count() :

print string.count('s') 

或findall() :

print len(re.findall("s", string))