题目描述
统计字符串中每个字符出现的频率,返回一个字典,键为字符,值为出现次数。按频率从高到低排序输出。
示例
输入:s = "hello world"
输出:{'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
提示
使用 collections.Counter 可以一行完成频率统计,然后用 most_common() 方法按频率排序。
参考答案
from collections import Counter
def char_frequency(s):
"""统计字符串中每个字符的频率"""
counter = Counter(s)
# 按频率从高到低排序
return dict(counter.most_common())
# 测试
result = char_frequency("hello world")
print(result)
# {'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
# 也可以分别输出每个字符
for char, count in Counter("hello world").most_common():
print(f"'{char}': {count}")