python - 字母计数词典

标签 python dictionary

我的家庭作业是编写一个名为 LetterCount() 的 Python 函数,它接受一个字符串作为参数并返回一个字母计数字典。但是,我的代码包含空格和逗号作为我不想要的字典的一部分。 你能帮帮我吗?如何从我的列表中删除空白区域?这是我的代码?

import string
def LetterCount(str):
    str= str.lower().strip()
    str = str.strip(string.punctuation)
    list1=list(str)
    lcDict= {}
    for l in list1:
        if l in lcDict:
            lcDict[l] +=1
        else:
            lcDict[l]= 1
    print lcDict

LetterCount("Abracadabra, Monsignor")

最佳答案

对于字母计数,最好的方法是使用字典。

s = "string is an immutable object"
def letter_count(s):
    d = {}
    for i in s:
        d[i] = d.get(i,0)+1
    return d

输出:

{'a': 2, ' ': 4, 'c': 1, 'b': 2, 'e': 2, 'g': 1, 'i': 3, 'j': 1, 'm': 2, 'l': 1, 'o': 1, 'n': 2, 's': 2, 'r': 1, 'u': 1, 't': 3}

关于python - 字母计数词典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5664494/

相关文章:

Python numpy 数组元素不改变值

c# - 将字典导出为 JSON,按键排序

Python:从迭代器内的列表中删除元素?

python - 如何在 Django 应用程序名称更改后编辑数据库表

python - 从 python 中的共享 fortran 库调用函数

python - token 错误 : EOF in multi-line statement

python - 如何从文件中读取两行并在 for 循环中创建动态键?

c# - 将 ListView 与对象集合相关联

c# - 将对象添加到 LINQ 中的字典值?

javascript - 如何在 CSS 或内联中增加 SVG 路径的宽度