Reputation:
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
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
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
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
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