For loop 如何编写对字符串中的每个字符进行计数的函数?

For loop 如何编写对字符串中的每个字符进行计数的函数?,for-loop,count,char,For Loop,Count,Char,我试图编写一个函数,计算每个字符在字符串s中出现的次数。首先,我想使用for循环 for i in range(len(s)): char = s[i] 在这里,我被卡住了。我将如何从这里开始?也许我需要计算字符串s中出现了多少次char 然后,输出应该是 count_char("practice") {'p' : 1, 'r' : 1, 'a' : 1, 'c' : 2, 't' : 1, 'i' : 1, 'e' : 1} 简单代码: def count_char(s

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

for i in range(len(s)):
char = s[i]
在这里,我被卡住了。我将如何从这里开始?也许我需要计算字符串
s
中出现了多少次
char

然后,输出应该是

count_char("practice")
{'p' : 1, 'r' : 1, 'a' : 1, 'c' : 2, 't' : 1, 'i' : 1, 'e' : 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}

我们如何按顺序打印字母,所以先打印p、r、a等等?已经修复了。对不起,对于范围内的i(len(s)),您能坚持使用
吗?已经再次修复了。