Python基礎:計算list中各個元素出現的頻率
知識
07-20
方法一
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)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
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()
- 1
方法二
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)
- 1
- 2
- 3
- 4
output:
[4, 4, 2, 1, 2]
※spring boot aop 方法請求參數日誌列印
※程序員該用哪種姿勢來理財
TAG:程序員小新人學習 |