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

问题

  • 某随机序列中,找到出现次数最高的三个元素,他们的出现次数是多少?
  • 对某英文文章的单词进行词频统计,找到出现次数最高的10个单词,出现次数是多少?

普通做法:

from random import randint

# #使用列表解析生成30个元素(在0~20范围内)
data = [randint(0,20) for _ in xrange(30)]
print type(data)

# 使用列表创建字典.data为key值,value为0
c = dict.fromkeys(data,0)
print c

# 使用for循环遍历data,遇到一个x,计数器c[x]就会增加1
for x in data:
    c[x] +=1
print c
c1= {k:v for k,v in c.iteritems()}
print c1

#根据字典的值对于字典的项进行排序,d[1]为值。d[0]为键
stat = sorted(c.iteritems(),key= lambda d:d[1],reverse=True)
print stat

某随机序列中,找到出现次数最高的三个元素

利用from collections import Counter

from random import randint
from collections import Counter
data = [randint(0,20) for _ in xrange(30)]
c2 = Counter(data)

#传入需要几个数值
smax = c2.most_common(5)
smin = c2.most_common()[:-6:-1]
print smax
print smin

对某英文文章的单词进行词频统计

import re

txt = open('code.txt').read()

# print txt

# 分割词:通过非字母字符
word = re.split('\W*',txt)

# print word

from collections import Counter
c3 = Counter(word)
# print c3

print c3.most_common(10)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容