首页 > 解决方案 > 字母计数功能

问题描述

我需要定义一个函数,该函数接受一个字符串并计算输入中字母的数量(仅小写),例如,如果我输入“jack”,它将返回:

a=1,b=0,c=1,d=0,...,j=1,k=1,...,z=0.

所以我实现了以下内容:

def l_count(str):
    str.lower()
    for ch in str:
        return str.count('a')

它只返回字符串中“a”的数量。由于我不想为所有字母表都这样做,所以我考虑过实现这样的列表理解:

al = [chr(i) for i in range(ord('a'),ord('z'))] 
def l_count(str):
    str.lower()
    for character in str:
        return str.count(al)

但我得到一个错误:

must be str, not list 

我不知道如何更改它,因为我得到了同样的错误。

标签: pythonlist-comprehensioncounteralphabeticalalphabetical-sort

解决方案


这是一种使用方法collections.Counter

from collections import Counter
from string import ascii_lowercase

x = 'jack'

c = Counter(dict.fromkeys(ascii_lowercase, 0))
c.update(Counter(x))

print(*(f'{k}={v}' for k, v in c.items()), sep=',')

a=1,b=0,c=1,d=0,e=0,f=0,g=0,h=0,i=0,j=1,k=1,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0

您可能希望为lowercase您的字符串添加逻辑,排除标点符号等。


推荐阅读