Count the frequency of an item in a python list
s there a function in Python that counts the number of occurrences of an item in Python? How python count frequency in list?
To count frequency in list you can do as shown :
To count the number of appearances: from collections import defaultdict
appearances = defaultdict(int)
for curr in a:
appearances[curr] += 1
To remove duplicates:
a = set(a)
Example:
import collections
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
counter=collections.Counter(a)
print(counter)
# Counter({1: 4, 2: 4, 3: 2, 5: 2, 4: 1})
print(counter.values())
# [4, 4, 2, 1, 2]
print(counter.keys())
# [1, 2, 3, 4, 5]
print(counter.most_common(3))
# [(1, 4), (2, 4), (3, 2)]