python3 中的Counter函数

Counter函数用来遍历列表中的所有元素 并将元素出现的次数记录下来

例如:

1.

alist = [1,1,3,99,88,2,2,2]
from collections import Counter
print(Counter(alist))

#输出结果为:({2: 3,1: 2,3: 1,99: 1,88: 1})

代表 2出现3次 1出现2次 3 99 88分别出现1次

2.

print(Counter(alist).most_common(1))
#输出结果为:[(2,3)]

代表 取出出现次数最多的元素

3.

print(Counter(alist).most_common(2))

#输出结果为:[(2,3),(1,2)]

代表 取出出现次数最多的前两个元素