python list统计

from random import randint

data = [randint(0, 20) for _ in xrange(30)]
print data
# [20, 4, 4, 20, 15, 9, 3, 13, 9, 8, 6, 16, 18, 7, 8, 12, 14, 5, 7, 7, 7, 5, 12, 4, 15, 3, 18, 1, 10, 9]
c = dict.fromkeys(data, 0)
print c
# {1: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 18: 0, 20: 0}
for x in data:
    c[x] += 1
print c
# {1: 1, 3: 2, 4: 3, 5: 2, 6: 1, 7: 4, 8: 2, 9: 3, 10: 1, 12: 2, 13: 1, 14: 1, 15: 2, 16: 1, 18: 2, 20: 2}
"""2"""
from collections import Counter

c2 = Counter(data)
print c2
# Counter({7: 4, 4: 3, 9: 3, 3: 2, 5: 2, 8: 2, 12: 2, 15: 2, 18: 2, 20: 2, 1: 1, 6: 1, 10: 1, 13: 1, 14: 1, 16: 1})
# 出现 频率最高的 3个元素
d = c2.most_common(3)
print d

 

posted @ 2019-04-07 22:26  AngDH  阅读(415)  评论(0编辑  收藏  举报