用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)

猜你喜欢

转载自www.cnblogs.com/banxiade/p/12638580.html