Home  >  Article  >  Backend Development  >  How to Efficiently Count Word Occurrences in a Python List?

How to Efficiently Count Word Occurrences in a Python List?

DDD
DDDOriginal
2024-10-30 17:02:26809browse

How to Efficiently Count Word Occurrences in a Python List?

Item Frequency Count in Python

How do you efficiently count the occurrences of each unique word in a given list? Consider the following code:

<code class="python">words = "apple banana apple strawberry banana lemon"
uniques = set(words.split())
freqs = [(item, words.split().count(item)) for item in uniques]
print(freqs)</code>

While this method works, it requires two iterations through the list, once to create the unique word set and again to count appearances. Can we optimize this?

Solution: Using the Counter Class

The Python collections module provides a Counter class specifically designed for this task. Here's how you can use it:

<code class="python">from collections import Counter
words = "apple banana apple strawberry banana lemon"
Counter(words.split())
# Output: Counter({'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1})</code>

The Counter class counts the occurrences of each item in the provided iterable, resulting in a dictionary where keys are unique items and values are their counts. This approach is more efficient as it only requires a single iteration through the input list.

The above is the detailed content of How to Efficiently Count Word Occurrences in a Python List?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn