📅  最后修改于: 2023-12-03 15:30:06.266000             🧑  作者: Mango
When we want to count the frequency of elements in an iterable in Python, one of the most commonly used tools is the collections.Counter()
class. In this article, we will cover everything you need to know about using Counter()
in Python.
collections.Counter()
is a Python class that is used for counting the frequency of elements in an iterable. It is a subclass of the built-in dictionary class and inherits all its methods.
To create a Counter()
object, we can pass an iterable (such as a list, tuple, or string) as an argument:
from collections import Counter
my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
my_counter = Counter(my_list)
print(my_counter)
This will output:
Counter({'apple': 3, 'banana': 2, 'orange': 1})
As we can see, the Counter()
object has counted the frequency of each element in the my_list
input.
One of the most common uses of Counter()
is finding the most common elements in a list. We can do this using the most_common()
method:
from collections import Counter
my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
my_counter = Counter(my_list)
most_common_elements = my_counter.most_common(2)
print(most_common_elements)
This will output:
[('apple', 3), ('banana', 2)]
As we can see, the most_common()
method returns a list of the most common elements and their frequencies, in descending order.
We can also update the counts in a Counter()
object using the update()
method:
from collections import Counter
my_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
my_counter = Counter(my_list)
new_list = ['orange', 'orange', 'orange', 'pear', 'apple']
my_counter.update(new_list)
print(my_counter)
This will output:
Counter({'orange': 4, 'apple': 4, 'banana': 2, 'pear': 1})
As we can see, the update()
method has added the counts of the new elements to the Counter()
object.
We can also perform arithmetic with Counter()
objects. For example, we can add two Counter()
objects together:
from collections import Counter
list1 = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter1 = Counter(list1)
list2 = ['orange', 'orange', 'orange', 'pear', 'apple']
counter2 = Counter(list2)
sum_counters = counter1 + counter2
print(sum_counters)
This will output:
Counter({'apple': 4, 'orange': 4, 'banana': 2, 'pear': 1})
As we can see, the resulting Counter()
object contains the element counts from both counter1
and counter2
.
collections.Counter()
is a powerful tool in Python for counting the frequency of elements in an iterable. It allows us to easily find the most common elements, update counts, and perform arithmetic with Counter()
objects.