python – How do I count occurrence of unique values inside a list
python – How do I count occurrence of unique values inside a list
In addition, use collections.Counter to refactor your code:
from collections import Counter
words = [a, b, c, a]
Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements frequency
Output:
[a, c, b]
[2, 1, 1]
You can use a set to remove duplicates, and then the len function to count the elements in the set:
len(set(new_words))
python – How do I count occurrence of unique values inside a list
values, counts = np.unique(words, return_counts=True)
More Detail
import numpy as np
words = [b, a, a, c, c, c]
values, counts = np.unique(words, return_counts=True)
The function numpy.unique returns sorted unique elements of the input list together with their counts:
[a, b, c]
[2, 1, 3]