對于一個清單,要統計出這個清單裡的所有元素個數,可以使用 collections.Counter 這個子產品。
以下是使用示例:

直接将一個清單作為參數放入 Counter 即可。
from collections import Counter
words = ['a', 'b', 'v', 't', 'a', 'g', 'g', 'c', 'v', 'v', 'a', 'f']
result = Counter(words)
已經得到統計的結果了,現在想要找出這個字典裡計數最多的幾個,可以使用 most_common() 函數來得到結果:
result.most_common(3)
Out[7]: [('a', 3), ('v', 3), ('g', 2)]
直接對結果的某個元素進行更新:
result['a'] += 1
通過某個清單對原有的 Counter 進行更新:
words2 = ['a', 'c', 'e', 'a', 'c', 'v', 'v']
result.update(words2)