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

    原文作者:a546167160
    原文地址: https://blog.csdn.net/a546167160/article/details/88524721
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞