How to find the most common element in a sequence

Preamble: There is a sequence of elements, want to know what element appears in the sequence the most times?

The Collections module’s Chinese Counter class is designed to address just such issues. It even has a very handy most_common() method to tell us the answer. The Counter object can be supplied with any hashable sequence of objects as input.

Example: Suppose we have a list with lists 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'
]
Count the number of occurrences of each element using Counter
words_counts=Counter(words)
# 3 elements that appear most frequently
top_three=words_counts.most_common(3)
# return the element and number of occurrences
print(top_three)
Underneath #Counter is a dictionary that maps elements to the number of times they appear, for example:
The number of occurrences of element [f]
print(words_counts['f'])
If you want to manually increase the number of counts, simply increment it
words_counts['f'] + = 1print(words_counts['f'])
If you want to manually increase the count, you can also use the update() method:
Add count to element [f] only once
words_counts.update('f')
print(words_counts['f'])
Increments all counts once
morewords=[
'a'.'b'.'c'.'d'.'e'.'f'
]
words_counts.update(morewords)
print(words_counts['f'])

Copy the code

Running results:

[('a'And 5), ('b'And 4), ('c', 3)]
2
3
4
5
Copy the code

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)
Copy the code

Running results:

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})
Copy the code

More Python tutorials will continue to be updated