【python cookbook】【数据结构与算法】12.找出序列中出现次数最多的元素

问题:找出一个元素序列中出现次数最多的元素是什么

解决方案:collections模块中的Counter类正是为此类问题所设计的。它的一个非常方便的most_common()方法直接告诉你答案。

# Determine the most common words in a list

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)]

# Example of merging in more words

morewords = [‘why‘,‘are‘,‘you‘,‘not‘,‘looking‘,‘in‘,‘my‘,‘eyes‘]
word_counts.update(morewords)  #使用update()增加计数
print(word_counts.most_common(3))
>>> ================================ RESTART ================================
>>>
[(‘eyes‘, 8), (‘the‘, 5), (‘look‘, 4)]
[(‘eyes‘, 9), (‘the‘, 5), (‘my‘, 4)]
>>> 

在底层实现中,Counter是一个字典,在元素和它们出现的次数间做了映射。

>>> word_counts
Counter({‘eyes‘: 9, ‘the‘: 5, ‘my‘: 4, ‘look‘: 4, ‘into‘: 3, ‘around‘: 2, ‘not‘: 2, "don‘t": 1, ‘under‘: 1, ‘are‘: 1, ‘looking‘: 1, "you‘re": 1, ‘you‘: 1, ‘why‘: 1, ‘in‘: 1})
>>> word_counts.most_common(3)  #top_three
[(‘eyes‘, 9), (‘the‘, 5), (‘my‘, 4)]
>>> word_counts[‘not‘]
2
>>> word_counts[‘eyes‘]
9
>>> word_counts[‘eyes‘]+1
10
>>> word_counts
Counter({‘eyes‘: 9, ‘the‘: 5, ‘my‘: 4, ‘look‘: 4, ‘into‘: 3, ‘around‘: 2, ‘not‘: 2, "don‘t": 1, ‘under‘: 1, ‘are‘: 1, ‘looking‘: 1, "you‘re": 1, ‘you‘: 1, ‘why‘: 1, ‘in‘: 1})
>>> word_counts[‘eyes‘]=word_counts[‘eyes‘]+1  #手动增加元素计数
>>> word_counts
Counter({‘eyes‘: 10, ‘the‘: 5, ‘my‘: 4, ‘look‘: 4, ‘into‘: 3, ‘around‘: 2, ‘not‘: 2, "don‘t": 1, ‘under‘: 1, ‘are‘: 1, ‘looking‘: 1, "you‘re": 1, ‘you‘: 1, ‘why‘: 1, ‘in‘: 1})
>>> 

增加元素出现次数可以通过手动进行增加,也可以借助update()方法;

另外,Counter对象另一个特性是它们可以同各种数学运算操作结合起来使用:

>>> a=Counter(words)
>>> a
Counter({‘eyes‘: 8, ‘the‘: 5, ‘look‘: 4, ‘my‘: 3, ‘into‘: 3, ‘around‘: 2, ‘under‘: 1, "you‘re": 1, ‘not‘: 1, "don‘t": 1})
>>> b=Counter(morewords)
>>> b
Counter({‘not‘: 1, ‘my‘: 1, ‘in‘: 1, ‘you‘: 1, ‘looking‘: 1, ‘are‘: 1, ‘eyes‘: 1, ‘why‘: 1})
>>> c=a+b
>>> c
Counter({‘eyes‘: 9, ‘the‘: 5, ‘my‘: 4, ‘look‘: 4, ‘into‘: 3, ‘around‘: 2, ‘not‘: 2, "don‘t": 1, ‘under‘: 1, ‘are‘: 1, ‘looking‘: 1, "you‘re": 1, ‘you‘: 1, ‘in‘: 1, ‘why‘: 1})
>>> # substract counts
>>> d=a-b
>>> d
Counter({‘eyes‘: 7, ‘the‘: 5, ‘look‘: 4, ‘into‘: 3, ‘my‘: 2, ‘around‘: 2, ‘under‘: 1, "you‘re": 1, "don‘t": 1})
>>> 

当面对任何需要对数据制表或计数的问题时,Counter对象都是你手边的得力工具。比起利用字典自己手写算法,更应采用该方式完成任务。

时间: 2024-08-05 11:12:18

【python cookbook】【数据结构与算法】12.找出序列中出现次数最多的元素的相关文章

Java实现找出数组中重复次数最多的元素以及个数

/**数组中元素重复最多的数 * @param array * @author shaobn * @param array */ public static void getMethod_4(int[] array){ Map<Integer, Integer> map = new HashMap<>(); int count = 0; int count_2 = 0; int temp = 0; for(int i=0;i<array.length;i=i+count){

给定n个正整数,找出它们中出现次数最多的数。如果这样的数有多个,请输出其中最小的一个。

ccf认证考试2013年12月第一题 问题描述 给定n个正整数,找出它们中出现次数最多的数.如果这样的数有多个,请输出其中最小的一个. 输入格式 输入的第一行只有一个正整数n(1 ≤ n ≤ 1000),表示数字的个数. 输入的第二行有n个整数s1, s2, -, sn (1 ≤ si ≤ 10000, 1 ≤ i ≤ n).相邻的数用空格分隔. 输出格式 输出这n个次数中出现次数最多的数.如果这样的数有多个,输出其中最小的一个. 样例输入 6 10 1 10 20 30 20 样例输出 10

找出字符串中出现次数最多的字符,和最大次数

/*找出字符串中出现次数最多的字符,和最大次数*/ function countMax(str){ var max = 0; // 记录出现的最大次数 var maxChar = ""; // 记录出现最多次数的字符 var counts = new Array(127); // 记录中间计算结果 for(var i = 0; i < counts.length; i++){ counts[i] = 0; } for(var i = 0; i < str.length; i

找出数组中出现次数超过一半的元素

题目:找出数组中出现次数超过一半的元素 解法:每次删除数组中两个不同的元素,删除后,要查找的那个元素的个数仍然超过删除后的元素总数的一半 #include <stdio.h> int half_number(int a[], int n) { if( a == NULL || n <= 0 ) return -1; int i, candidate; int times = 0; for( i=0; i<n; i++ ) { if( times == 0 ) { candidate

[PY3]——找出一个序列中出现次数最多的元素/collections.Counter 类的用法

问题 怎样找出一个序列中出现次数最多的元素呢? 解决方案 collections.Counter 类就是专门为这类问题而设计的, 它甚至有一个有用的 most_common() 方法直接给了你答案 collections.Counter 类 1. most_common(n)统计top_n from collections import Counter words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 't

python之Counter类:计算序列中出现次数最多的元素

Counter类:计算序列中出现次数最多的元素 1 from collections import Counter 2 3 c = Counter('abcdefaddffccef') 4 print('完整的Counter对象:', c) 5 6 a_times = c['a'] 7 print('元素a出现的次数:', a_times) 8 9 c_most = c.most_common(3) 10 print('出现次数最多的三个元素:', c_most) 11 12 times_dic

算法之找出数组中出现次数大于n/m的元素

最经典的题目莫过于是: 在一个数组中找出出现次数超过n/2的元素?更进一步的,找出数组中出现次数大于n/3的所有元素? 注:这里有一个很重要的事实,那就是出现次数大于n/m的元素的个数至多为(m-1)个,比如出现次数大于n/3的至多只有两个. 关于这一类题目的解题思路,可以先讲一个游戏 称作 "俄罗斯方块".这里的规则是每一行的元素要完全不一样,一样的元素则总是在同一列,如果最下面的行已经被填满,那么消除最下面的行. 例如在数组 A = {7,3,3,7,4,3,4,7,3,4,3,4

js常会问的问题:找出字符串中出现次数最多的字符。

一.循环obj let testStr = 'asdasddsfdsfadsfdghdadsdfdgdasd'; function getMax(str) { let obj = {}; for(let i in str) { if(obj[str[i]]) { obj[str[i]]++; }else{ obj[str[i]] = 1; } } let keys = Object.keys(obj); // 获取对象中所有key的值返回数组 let values = Object.values

C# 找出数组中重复次数最多的数值

给定一个int数组,里面存在重复的数值,如何找到重复次数最多的数值呢? 这是在某社区上有人提出的问题,我想到的解决方法是分组. 1.先对数组中的所有元素进行分组,那么,重复的数值肯定会被放到一组中: 2.将分组进行排序,排序条件是分组中的元素个数: 3.元素数量最多的那个分组中的数值就是重复次数最多的. 基于以上思路,可以写出以下代码: // 示例数组,90重复4次,1重复2次,3重复3次 int[] arr = { 1, 1, 3, 3, 3, 7, 50, 15, 15, 90, 90, 9