用python统计list中各元素出现的次数(同理统计字符串中各字符出现的次数)

统计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)

 

posted @ 2020-04-05 19:18  chang不二  阅读(3214)  评论(0编辑  收藏  举报