Given an unordered list of values, determining the frequency of each element is a common programming task. This guide explains how to achieve this using the collections.Counter module in Python.
In Python 2.7 or later, the collections.Counter module provides an efficient means of counting element occurrences. By simply passing your list as an argument to the Counter constructor, you can obtain a dictionary-like object that maps each unique element to its count.
import collections a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2] counter = collections.Counter(a)
Now, you can use the Counter object to retrieve the frequency of each element. Here are a few common operations:
[counter[x] for x in sorted(counter.keys())]
If you are using Python 2.6 or older, you will need to download and install the Counter implementation available online.
The above is the detailed content of How Can I Efficiently Count Element Frequencies in a Python List?. For more information, please follow other related articles on the PHP Chinese website!