counter()
作用:在一个数组内,遍历所有元素,将元素出现的次数记下来
用法:
from collections import Counter
Counter(a)
1 求数组中每个元素出现的次数
>>> from collections import Counter
>>> a = [1,4,2,3,2,3,4,2]
>>> print(Counter(a))
Counter({2: 3, 4: 2, 3: 2, 1: 1})
2 求数组中出现次数最多的元素
>>> from collections import Counter
>>> a = [1,4,2,3,2,3,4,2]
>>> print(Counter(a).most_common(1))
[(2, 3)]
>>> from collections import Counter
>>> a = [1,4,2,3,2,3,4,2]
>>> print(Counter(a).most_common(2))
[(2, 3), (4, 2)]
注:
Counter(a)可以打印出数组中a中每个元素出现的次数;
Counter(a).most_common(2)可以打印出数组中出现次数最多的元素。参数2表示输出几个出现次数最多的元素。
转载自
https://blog.csdn.net/qq_24753293/article/details/78334140