counter()
作用:在一个数组内,遍历所有元素,将元素出现的次数记下来
用法:
复制代码
1
2
3from collections import Counter Counter(a)
1 求数组中每个元素出现的次数
复制代码
1
2
3
4
5>>> 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 求数组中出现次数最多的元素
复制代码
1
2
3
4
5>>> from collections import Counter >>> a = [1,4,2,3,2,3,4,2] >>> print(Counter(a).most_common(1)) [(2, 3)]
复制代码
1
2
3
4
5>>> 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
最后
以上就是超级啤酒最近收集整理的关于collections模块下的counter函数用法的全部内容,更多相关collections模块下内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复