Home > Article > Backend Development > Python implementation to find the element that appears most often in a sequence
1. Requirements
We have a sequence of elements and want to know what is the element that appears most often in the sequence?2. Solution
collections module China’s Counter class is designed for this type of problem. It even has a very convenient most_common() method that tells us the answer. Any hashable sequence of objects can be provided as input to a Counter object.
Example: Suppose there is a list with some columns of words, and we want to find out which words appear most frequently:
from collections import Counter words=[ 'a','b','c','d','e','f', 'a','b','c','d','e','f', 'a','b','c', 'a','b', 'a' ] #利用Counter统计每个元素出现的个数 words_counts=Counter(words) #出现次数最多的3个元素 top_three=words_counts.most_common(3) #返回元素和出现次数 print(top_three) #Counter底层是一个字典,可以在元素和他们出现的次数之间做映射,例如: #输出元素【f】出现的次数 print(words_counts['f']) #如果想手动增加计数个数,只需要简单的自增 words_counts['f']+=1 print(words_counts['f']) #如果想手动增加计数个数,还可以使用update()方法: #只针对元素【f】增加一次计数 words_counts.update('f') print(words_counts['f']) #为所有计数增加一次 morewords=[ 'a','b','c','d','e','f' ] words_counts.update(morewords) print(words_counts['f'])
Running results:
[('a', 5), ('b', 4), ('c', 3)] 2 3 4 5
Another little-known feature of Counter objects is that they can be easily combined with various mathematical operations.
from collections import Counter words1=[ 'a','b','c','d','e','f', 'a','b','c','d','e','f', 'a','b','c', 'a','b', 'a' ] words2=[ 'a','b','c','d','e','f', 'a','b','c', 'a','b', 'a' ] one=Counter(words1) two=Counter(words2) print(one) print(two) three=one+two print(three) four=one-two print(four)
Run result:
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 2, 'f': 2}) Counter({'a': 4, 'b': 3, 'c': 2, 'd': 1, 'e': 1, 'f': 1}) Counter({'a': 9, 'b': 7, 'c': 5, 'd': 3, 'e': 3, 'f': 3}) Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1})
The above is the detailed content of Python implementation to find the element that appears most often in a sequence. For more information, please follow other related articles on the PHP Chinese website!