2-3统计序列中元素出现的频度

# -*- coding:utf-8 -*-

from random import randint
from collections import Counter
import re

data = [randint(0, 20) for _ in xrange(30)]

# 解决方案1:
c = dict.fromkeys(data, 0)  # 得到初始的字典,目前每个元素的键值是0
for x in data:
    c[x] += 1


# 解决方案2:
# 将序列传入Counter的构造器,得到Counter对象是元素频度的字典
# Counter.most_common(n)方法得到频度最高的n个元素的列表

c2 = Counter(data)  # 统计出来的c2就是上面c字典的样子
c2.most_common(3)
# 结果:
# [(5, 5), (11, 4), (2, 3)]

# 复杂例子(很多字符串):
txt = open('CodingStyle').read()
c3 = Counter(re.split('\W+', txt))  # 以非字母的字符为分割符
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值