Python 统计字符串里每个字符出现的次数的三种方法

dic.setdefault(char, defaultnum)

count = {}
for character in message:
    count.setdefault(character, 0) # 确保了键存在于 count 字典中(默认值是 0)
    count[character] = count[character] + 1

if else

count = {}
for i in message:
    if i not in count:
        count[i] = 1
    else:
        count[i] += 1

利用collections库的Counter方法

from collections import Counter
res = Counter(sting)

得到一个Counter{‘a’: 5, ‘b’: 8}
dict ( c ) # 将c中的键值对转为字典
c.items( ) # 转为(elem, cnt)格式的列表

原文:https://blog.csdn.net/whjay520/article/details/82996665

你可能感兴趣的:(python)