Home >Backend Development >Python Tutorial >How to Efficiently Count Item Frequencies in Python: Using the Counter Class?
Problem:
Finding the number of occurrences of each item in a list of words is a common task in text processing. A straightforward approach involves creating a set of unique words and then counting their instances within the list. However, this method is inefficient as it iterates twice over the list.
More Efficient and Pythonic Solution:
To improve efficiency, Python offers the collections.Counter class, specifically designed for counting items in a collection.
Code:
<code class="python">from collections import Counter words = "apple banana apple strawberry banana lemon" print(Counter(words.split()))</code>
Output:
Counter({'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1})
Advantages:
The above is the detailed content of How to Efficiently Count Item Frequencies in Python: Using the Counter Class?. For more information, please follow other related articles on the PHP Chinese website!