Python Collections.Counter()函数详解(统计字符频率
发布日期:2021-11-15 14:58:09 浏览次数:37 分类:技术文章

本文共 1882 字,大约阅读时间需要 6 分钟。

前言

以后出现统计字符的题目,不要再先排序,在一个一个统计;或者使用dict。可以使用更简单的Counter()函数

一、Collections模块的综述

Collections模块使用了高性能容器数据类型,并且包含许多有用的数据结构,它的性能超过了内置的类型如 list,dict and tuple等。

二、Counter概念和使用

Counter是一个容器,用来统计值出现的频率

使用前需要先导入模块

>>>from collections import Counter

1.初始化Counter

Counter支持三种形式的初始化,在它的构造器被调用时可以传入可迭代的序列(字符串,列表,元组等),包含keys和values的字典或mapping`

>>>Counter(['a', 'b', 'c', 'a', 'b', 'b'])Counter({
'b': 3, 'a': 2, 'c': 1})>>>Counter({
'a':2, 'b':3, 'c':1})Counter({
'b': 3, 'a': 2, 'c': 1})>>>Counter(a=2, b=3, c=1)Counter({
'b': 3, 'a': 2, 'c': 1})

2.创建并且更新Counter

初始可以创建空的Counter,随后用update()添加元素

>>>a=Counter()>>>a.update('adhasfa')>>>aCounter({
'a': 3, 'd': 1, 'h': 1, 's': 1, 'f': 1})>>>a.update({
'a':2,'f':1})>>>aCounter({
'a': 5, 'f': 2, 'd': 1, 'h': 1, 's': 1})#所以update但是在前者的基础上进行的,尽管传入的类型不一样

3.访问Counter的元素

从上面的结果可以发现,Counter很像字典…的确是,可以用访问字典的方式访问Counter

>>> a.items()dict_items([('a', 5), ('d', 1), ('h', 1), ('s', 1), ('f', 2)])>>> a.keys()dict_keys(['a', 'd', 'h', 's', 'f'])>>> a.values()dict_values([5, 1, 1, 1, 2])>>>a['a']5>>>a['a']=9  #直接对Counter进行修改>>>aCounter({
'a': 9, 'f': 2, 'd': 1, 'h': 1, 's': 1})

4.most_common()函数

根据Counter().most_common(k)可以返回出现频率最高的k个值和他们相应的频率,默认是返回所有值

>>> a.most_common() 返回的是列表类型[('a', 9), ('f', 2), ('d', 1), ('h', 1), ('s', 1)]

5.算术运算和集合操作

Counter对象支持算术运算和集合操作

>>>c1=Counter(['a', 'b', 'c', 'a', 'b', 'b'])>>>c2=Counter('alphabet')>>>c1Counter({
'b': 3, 'a': 2, 'c': 1})>>>c2Counter({
'a': 2, 'b': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 1, 't': 1})#相加>>>c1+c2Counter({
'a': 4, 'b': 4, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})#相减>>>c1-c2Counter({
'b': 2, 'c': 1})#交集>>>c1&c2Counter({
'a': 2, 'b': 1})#并集>>>c1|c2Counter({
'b': 3, 'a': 2, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})

参考资料

http://www.doughellmann.com/PyMOTW/collections/

http://docs.python.org/2/library/collections.html#collections.Counter

转载地址:https://blog.csdn.net/qq_39751320/article/details/104354745 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Python map()函数讲解
下一篇:Python reduce()函数的用法详解

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月06日 04时25分02秒