user16341274
user16341274

Reputation:

Occurrence of an element in list

I want to get the frequency of each value in a given list.

fruits = ["apple", "banana", "cherry", "apple", "banana"]
counts = [fruits.count(x) for x in fruits]
print(counts)
>>> [2, 2, 1, 2, 2] # "apple", "banana", "cherry", "apple", "banana"

Desired Output

>>> [2, 2, 1] # "apple", "banana", "cherry"

Secondly; what might be the most computationally efficient way of doing this?

Upvotes: 0

Views: 295

Answers (4)

theunknownSAI
theunknownSAI

Reputation: 330

Using dictionary to count the frequency

fruits = ["apple", "banana", "cherry", "apple", "banana"]
freq = {}
for fruit in fruits:
    freq[fruit] = freq.get(fruit,0) + 1
print(list(freq.values()))

Upvotes: 0

Epsi95
Epsi95

Reputation: 9047

Simply use a dict and count the frequency.

fruits = ["apple", "banana", "cherry", "apple", "banana"]
counter_map = {}

for each_fruit in fruits:
    if each_fruit in counter_map:
        counter_map[each_fruit] += 1
    else:
        counter_map[each_fruit] = 1
        
print(list(counter_map.values())) #[2, 2, 1]

Upvotes: 0

RandomCoder59
RandomCoder59

Reputation: 183

You can create a set(fruits) to remove duplicates and then count the elements from the fruits list:

fruits = ["apple", "banana", "cherry", "apple", "banana"]
set_fruits = set(fruits)
counts = [fruits.count(x) for x in set_fruits]
print(counts)

Upvotes: 1

user2390182
user2390182

Reputation: 73450

Use a collections.Counter:

from collections import Counter

[*Counter(fruits).values()]
# [2, 2, 1]

This collects all counts in a single iteration.

Upvotes: 1

Related Questions