统计字符串中字符出现的次数-Python

时间:2022-07-22
本文章向大家介绍统计字符串中字符出现的次数-Python,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

方法一:

list1 = ['a', 'a', 'b', 'c', 'c', 'c', 'c']
dict_cnt = {}
for value in list1:
    dict_cnt[value] = dict_cnt.get(value, 0) + 1
print(dict_cnt)

方法二:

list1 = ['a', 'a', 'b', 'c', 'c', 'c', 'c']
dict_cnt = {}
for item in list1:
    if item in dict_cnt:  # 直接判断key在不在字典中
        dict_cnt[item] += 1
    else:
        dict_cnt[item] = 1
print(dict_cnt)