Python 3はシーケンス内の要素の出現頻度をどのように統計するか
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from random import randint
data = [randint(0, 20) for _ in range(30)]
1.反復
''' '''
# , , 0
d = {}
for i in data:
d[i] = 0
# fromkeys()
# seq ,value
# d = dict.fromkeys(data, 0)
# , 1
for i in data:
d[i] += 1
print(d)
''' '''
# get() ,
d2 = {}
for i in data:
d2[i] = d2.get(i, 0) + 1
print(d2)
2.標準ライブラリの
collections.Counter
を使用して要素の出現頻度を統計するfrom collections import Counter
d3 = Counter(data)
print(dict(d3))
# most_common(3) 3
print(d3.most_common(3))
実行結果:
Geek-Mac:Downloads zhangyi$ python3 Nice.py
{5: 3, 19: 2, 20: 1, 15: 2, 10: 4, 3: 2, 2: 3, 8: 1, 1: 4, 4: 2, 7: 1, 18: 1, 16: 1, 9: 1, 6: 1, 0: 1}
{5: 3, 19: 2, 20: 1, 15: 2, 10: 4, 3: 2, 2: 3, 8: 1, 1: 4, 4: 2, 7: 1, 18: 1, 16: 1, 9: 1, 6: 1, 0: 1}
{5: 3, 19: 2, 20: 1, 15: 2, 10: 4, 3: 2, 2: 3, 8: 1, 1: 4, 4: 2, 7: 1, 18: 1, 16: 1, 9: 1, 6: 1, 0: 1}
[(10, 4), (1, 4), (5, 3)]