如何统计序列中元素的出现频度

1、实际案例

1.1 某随机序列[12,5,6,4,6,5,5,7,...]中,找到出现次数最高的3个元素,它们出现的次数是多少?

1.2 对某英文文章的单词,进行词频统计,找出出现次数最高的十个单词,它们出现的次数是多少?

2、解决方案

2.1 创建随机序列,   构造字典,默认初始值为0,循环遍历data,对每个元素进行从0递增

from random import randint
data = [randint(0,20) for _ in xrange(30)]
c = dict.fromkeys(data,0)
print(c)
for x in data:
    c[x] += 1

2.1 使用collections.Counter对象

将序列传入Counter构造器,得到Counter对象是元素频度的字典。

Counter.most_common(n)方法得到频度最高的n个元素的列表

from collection import Counter
c2 = Counter(data)
print(c2[10])

c2.most_common(3)



猜你喜欢

转载自blog.csdn.net/gis_bt/article/details/80301794