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)] |
res = {} |
Solution 2
Construct a dictionary based on the data, initial values are 0
res2 = dict.fromkeys(data_freq, 0) |
Construct the count dictionary
for d in data_freq: |
To select the top 3, can use heapq
import heapq |
Counter
It’s very easy to do this with Counter from collections.
from collections import Counter |
Use most_common method
c = Counter(data_freq) |
An example of word count
Read a file containing zen of python and perform a word count.
Use RegEx to split words
import re |