python高效编程技巧3(如何统计序列中元素出现的频率)
#!/usr/bin/env python# -*- coding:utf-8 -*-from random import randint# 1、方案1data = [randint(0, 20) for _ in xrange(30)]# fromkey函数,以data中的每个值作为key,以0作为值,生成字典类型{1:0,...}c = dict.fromkeys(data, 0)f
·
#!/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
更多推荐
所有评论(0)