Item Frequency Count in Python with Enhanced Efficiency
Counting the occurrence of items within a list is a common programming task. This question explores a more efficient approach to this problem in Python.
The initial code presented, while functional, involves iterating through the list twice, leading to suboptimal performance. The key challenge lies in finding a Pythonic way to count item occurrences without redundant passes through the list.
The solution lies in utilizing the Counter class from the collections module. Specifically designed for frequency counting, Counter offers a concise and efficient way to achieve the desired result. The following code demonstrates its usage:
from collections import Counter
words = "apple banana apple strawberry banana lemon"
Counter(words.split())
This code snippet splits the input string into individual words and passes the resulting list to Counter. The result is a dictionary-like object where keys represent unique words, and values represent their corresponding counts. In this example, the output would be:
Counter({'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1})
The Counter class internally employs a hash table to store data, providing constant-time lookup and insertion operations. This approach eliminates the need for a second iteration and significantly improves the performance of the item frequency count.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3