python学习:counter计数
来源:互联网 发布:linux stdin 编辑:程序博客网 时间:2024/05/22 13:00
一:定义一个list数组,求数组中每个元素出现的次数
如果用java来实现,是一个比较复杂的,需要遍历数组list。
但是python很简单:看代码
a = [1,4,2,3,2,3,4,2]from collections import Counterprint Counter(a)
打印结果:
Counter({2: 3, 3: 2, 4: 2, 1: 1})
结果表示:元素2出现了3次;元素3出现了2次;元素4出现了2次;元素1出现了1次。
二:求数组中出现次数最多的元素
直接看代码:
a = [1,4,2,3,2,3,4,2]from collections import Counterprint Counter(a).most_commo(1)
运行结果:
[(2, 3)]
继续修改代码:
a = [1,4,2,3,2,3,4,2]from collections import Counterprint Counter(a)print Counter(a).most_common(2)
运行结果:
[(2, 3), (3, 2)]
三:总结
(1)从Collections集合模块中引入集合类Counter
(2)Counter(a)可以打印出数组a中每个元素出现的次数
(3)Counter(a).most_common(2)可以打印出数组中出现次数最多的元素。参数2表示的含义是:输出几个出现次数最多的元素。
0 0
- python学习:counter计数
- python学习——Counter计数方法
- Python Counter()计数工具
- python-Counter计数函数
- Python Counter()计数工具
- Python中Counter计数统计
- python使用Collections.Counter进行计数
- Python:使用Counter进行计数统计及collections模块
- python Counter
- 计数时使用Counter计数对象
- Python使用collections的Counter类对字符串、列表、字典的数据元素进行计数
- python之collections模块Counter类使用学习
- enumerate Counter in python
- Python Collections Counter
- Python Counter() 的实现
- python collections Counter
- python Counter模块
- python中counter()记数
- 算法导论 - 归并排序的 C 语言实现
- 理解gamma校正
- Asterisk CALL文件使用说明
- 多个UIViewController中复用NIB文件
- 线程同步(VC_Win32)
- python学习:counter计数
- 如何不绑定脚本且不继承MonoBehaviour做U3D的开发
- leetcode_2_Add Two Numbers
- USACO2.1.1 The Castle (castle)
- Asterisk 关于抢接问题
- 记录在2015-01-27
- TiledMap出现小白线
- web请求乱码的机关
- 客户端PureMVC框架与轻型U3D服务器Tnet结合图解