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

How to Efficiently Count Word Occurrences in a Python List?

DDD
Release: 2024-10-30 17:02:26
Original
958 people have browsed it

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>
Copy after login

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>
Copy after login

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 of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template