【Python】計算list中各個元素出現的頻率

#方法一

from collections import Counter

list = [59, 138, 13, 1367, 158, 35, 572, 43, 10, 34, 572, 572, 44, 12, 1345, 7, 21, 59, 10]
list.sort()

counter = Counter(list)
print(counter)

output:

Counter({572: 3, 10: 2, 59: 2, 7: 1, 12: 1, 13: 1, 21: 1, 34: 1, 35: 1, 43: 1, 44: 1, 138: 1, 158: 1, 1345: 1, 1367: 1})

如果想要把counter輸出的結果,按照頻率從高到低排列,可以這樣

counter.most_common()

#方法二

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
from itertools import groupby
b = [len(list(group)) for key, group in groupby(a)]
print(b)

output:
[4, 4, 2, 1, 2]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章