统计 list 中各元素出现的次数, 下面的方法也适用于统计字符串中各字符出现的次数
1, 用字典的形式来处理
- a = "abhcjdjje"
- a_dict = {
- }
- for i in a:
- a_dict[i] = a.count(i)
- print(a_dict)
2, 用 count 函数直接打印出来
- L = [2,4,5,6,2,6,0,4]
- for i in L:
- print("%d 的次数:%d"%(i,L.count(i)))
3, 用 collections 的 Counter 函数
- from collections import Counter
- L = [2,4,5,6,2,6,0,4]
- result = Counter(L)
- print(result)
来源: http://www.bubuko.com/infodetail-3493443.html