#!/usr/bin/env python
# -*- coding:utf-8 -*-
from random import randint

# 1、方案1
data = [randint(0, 20) for _ in xrange(30)]
# fromkey函数,以data中的每个值作为key,以0作为值,生成字典类型{1:0,...}
c = dict.fromkeys(data, 0)
for x in data:
    c[x] += 1
print c

# 2、方案2:使用collections.Counter对象
from collections import Counter

data = [randint(0, 20) for _ in xrange(30)]
# 将序列传入Counter的构造器,得到Counter对象是元素频度的字典
c2 = Counter(data)
# 使用Counter.most_common(n)方法得到频度最高的n个元素的列表
max = c2.most_common(1)
print max
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐