Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Item frequency count in Python

Assume I have a list of words, and I want to find the number of times each word appears in that list.

An obvious way to do this is:

words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split().count(item)) for item in uniques] print(freqs) 

But I find this code not very good, because the program runs through the word list twice, once to build the set, and a second time to count the number of appearances.

Of course, I could write a function to run through the list and do the counting, but that wouldn't be so Pythonic. So, is there a more efficient and Pythonic way?

like image 273
Daniyar Avatar asked May 21 '09 15:05

Daniyar


People also ask

How do you count items in a list in Python?

The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.

How do you count the frequency of a string in a list?

We can use the counter() method from the collections module to count the frequency of elements in a list. The counter() method takes an iterable object as an input argument. It returns a Counter object which stores the frequency of all the elements in the form of key-value pairs.

What is a frequency count?

The tally or frequency count is the calculation of how many people fit into a certain category or the number of times a characteristic occurs. This calculation is expressed by both the absolute (actual number) and relative (percentage) totals.


1 Answers

The Counter class in the collections module is purpose built to solve this type of problem:

from collections import Counter words = "apple banana apple strawberry banana lemon" Counter(words.split()) # Counter({'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1}) 
like image 183
sykora Avatar answered Sep 20 '22 04:09

sykora