1.12.在序列中查找出现次数最多的元素
2014-09-29 20:39
387 查看
解决方法
collections.Counter类就是为此设计的,它甚至提供了
most_common()方法来解决你的问题。
举个例子,查找
words中的出现次数最多的词:
words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] from collections import Counter word_counts = Counter(words) top_three = word_counts.most_common(3) print(top_three) # Outputs [('eyes', 8), ('the', 5), ('look', 4)]
讨论
Counter对象可以“吞吃”任何哈希元素的序列。一个
Counter是映射元素到出现次数的字典。e.g:
>>> word_counts['not'] 1 >>> word_counts['eyes'] 8 >>>
如果想手动添加计数,只需简单添加:
>>> morewords = ['why','are','you','not','looking','in','my','eyes'] >>> for word in morewords: ... word_counts[word] += 1 ... >>> word_counts['eyes'] 9 >>>
还可以使用
update()函数:
>>> word_counts.update(morewords) >>>
更有趣的是,
Counter实例可以简单的做大量的数学运算,e.g:
>>> a = Counter(words) >>> b = Counter(morewords) >>> a Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2, "you're": 1, "don't": 1, 'under': 1, 'not': 1}) >>> b Counter({'eyes': 1, 'looking': 1, 'are': 1, 'in': 1, 'not': 1, 'you': 1, 'my': 1, 'why': 1}) >>> # Combine counts >>> c = a + b >>> c Counter({'eyes': 9, 'the': 5, 'look': 4, 'my': 4, 'into': 3, 'not': 2, 'around': 2, "you're": 1, "don't": 1, 'in': 1, 'why': 1, 'looking': 1, 'are': 1, 'under': 1, 'you': 1}) >>> # Subtract counts>>> d = a - b >>> d Counter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2, "you're": 1, "don't": 1, 'under': 1}) >>>
无需多言,
Counter对象在对数据做列表和计数上是及其有用的工具。用它你无需用字典写解决方法了。
相关文章推荐
- python找出序列中出现次数最多的元素之Counter对象
- python 找出序列中出现次数最多的元素方法。
- [00012] 序列中出现次数最多的元素
- Python实用黑科技——找出序列里面出现次数最多的元素
- python 找出序列中出现次数最多的元素方法
- [PY3]——找出一个序列中出现次数最多的元素/collections.Counter 类的用法
- Python cookbook(数据结构与算法)找出序列中出现次数最多的元素算法示例
- 程序员面试题目总结--数组(三)【旋转数组的最小数字、旋转数组中查找指定数、两个排序数组所有元素中间值、数组中重复次数最多的数、数组中出现次数超过一半的数】
- 寻找容器vector中出现最多的元素以及出现的次数
- 输出列表中出现次数最多的元素 分类: python 2013-01-15 15:25 990人阅读 评论(0) 收藏
- 找出数组里面元素出现次数最多的问题
- 随机生成长度为100的数组,数组元素为1到10,统计出现次数最多和最少的元素
- 给定一个整数序列,确定这个序列中出现次数最多的整数和它出现的次数
- 求一个数组中重复元素出现最多值,最大的元素及出现次数,次数相同时,取最大值,优先考虑次数
- 查找出现次数大于n/k的重复元素 ---非多重集算法
- matlab获取向量中出现次数最多的元素
- 找出数组里面元素出现次数最多的问题
- LINQ 获取当前数组中出现次数最多的元素
- 在字符串中查找出现次数最多的子串
- asp.net 实现获取一个集合数组中出现次数最多的元素