如何编写一个计算字符串中每个字符的函数?

时间:2021-04-15 09:44:10

标签: for-loop count char

我正在尝试编写一个函数来计算字符串 s 中每个字符出现的次数。首先,我想使用 for 循环

for i in range(len(s)):
char = s[i]

在这里,我被卡住了。我将如何从这里开始?也许我需要计算 char 在字符串 s 中出现了多少次。

那么,输出应该是...

count_char("practice")
{'p' : 1, 'r' : 1, 'a' : 1, 'c' : 2, 't' : 1, 'i' : 1, 'e' : 1}

1 个答案:

答案 0 :(得分:1)

简单代码:

def count_char(s):
    result = {}
    for i in range(len(s)):
        result[s[i]] = s.count(s[i])
    return result

print(count_char("practice"))

列表理解代码:

def count_char(s):
    return {s[i]:s.count(s[i]) for i in range(len(s))}

print(count_char("practice"))

结果:

{'p': 1, 'r': 1, 'a': 1, 'c': 2, 't': 1, 'i': 1, 'e': 1}