【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]

你可能感兴趣的:(python)