您的位置:首页 > 编程语言 > Python开发

python高效编程技巧3(如何统计序列中元素出现的频率)

2017-10-16 19:21 776 查看
#!/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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python