您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页py编程技巧-1.3-如何统计序列中元素的出现频度

py编程技巧-1.3-如何统计序列中元素的出现频度

来源:二三娱乐

实际案例

  1. 某随机序列中,找到出现次数最高的三个元素,他们的出现次数是多少?
  2. 对某英文文章的单词进行词频统计,找到出现次数最高的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 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)

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务