How to count the frequencies of elements in a list?
- Convert to a dictionary with key is the element, value is the frequency
- Sort the dictionary
Solution 1
First construct a list with repetitive elements:
data_freq = [randint(0,10) for _ in range(30)]
Python
res = {}
for ele in data_freq:
if ele in res:
res[ele] += 1
else:
res[ele] = 1
res = dict(sorted(res.items(), key=lambda x: x[1], reverse=True))
Python
Solution 2
Construct a dictionary based on the data, initial values are 0
res2 = dict.fromkeys(data_freq, 0)
Python
Construct the count dictionary
for d in data_freq:
res2[d] += 1
res = dict(sorted(res.items(), key=lambda x:x[1], reverse=True))
Python
To select the top 3, can use heapq
import heapq
heapq.nlargetst(3, ((v,k) for k,v in d.items())
Python
Counter
It’s very easy to do this with Counter from collections.
from collections import Counter
Counter(data_freq)
Python
Use most_common method
c = Counter(data_freq)
c.most_common()
Python
An example of word count
Read a file containing zen of python and perform a word count.
Use RegEx to split words
import re
wl = re.split('\W+', zen)
wc = Counter(wl)
wc.most_common(3)
Python