Python Counter()计数工具
Table of Contents
class collections.Counter([iterable-or-mapping])
Counter
是实现的 dict
的一个子类,可以用来方便地计数。
例子
举个计数的例子,需要统计一个文件中,每个单词出现的次数。实现方法如下
# 普通青年
d = {}
with open('/etc/passwd') as f:
for line in f:
for word in line.strip().split(':'):
if word not in d:
d[word] = 1
else:
d[word] += 1
# 文艺青年
d = defaultdict(int)
with open('/etc/passwd') as f:
for line in f:
for word in line.strip().split(':'):
d[word] += 1
# 棒棒的青年
word_counts = Counter()
with open('/etc/passwd') as f:
for line in f:
word_counts.update(line.strip().split(':'))
使用实例
可以像下面例子一样来创建一个 Counter
:
>>> c = Counter() # 创建一个新的空counter
>>> c = Counter('abcasdf') # 一个迭代对象生成的counter
>>> c = Counter({'red': 4, 'yello': 2}) # 一个映射生成的counter
>>> c = Counter(cats=2, dogs=5) # 关键字参数生成的counter
# counter 生成counter, 虽然这里并没有什么用
>>> from collections import Counter
>>> c = Counter('abcasd')
>>> c
Counter({'a': 2, 'c': 1, 'b': 1, 's': 1, 'd': 1})
>>> c2 = Counter(c)
>>> c2
Counter({'a': 2, 'c': 1, 'b': 1, 's': 1, 'd': 1})
因为 Counter
实现了字典的 __missing__
方法, 所以当访问不存在的key的时候,返回值为0:
>>> c = Counter(['apple', 'pear'])
>>> c['orange']
0
counter
常用的方法:
# elements() 按照counter的计数,重复返回元素
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
# most_common(n) 按照counter的计数,按照降序,返回前n项组成的list; n忽略时返回全部
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
# subtract([iterable-or-mapping]) counter按照相应的元素,计数相减
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
>>> c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
# update([iterable-or-mapping]) 不同于字典的update方法,这里更新counter时,相同的key的value值相加而不是覆盖
# 实例化 Counter 时, 实际也是调用这个方法
# Counter 间的数学集合操作
>>> c = Counter(a=3, b=1, c=5)
>>> d = Counter(a=1, b=2, d=4)
>>> c + d # counter相加, 相同的key的value相加
Counter({'c': 5, 'a': 4, 'd': 4, 'b': 3})
>>> c - d # counter相减, 相同的key的value相减,只保留正值得value
Counter({'c': 5, 'a': 2})
>>> c & d # 交集: 取两者都有的key,value取小的那一个
Counter({'a': 1, 'b': 1})
>>> c | d # 并集: 汇聚所有的key, key相同的情况下,取大的value
Counter({'c': 5, 'd': 4, 'a': 3, 'b': 2})
常见做法:
sum(c.values()) # 继承自字典的.values()方法返回values的列表,再求和
c.clear() # 继承自字典的.clear()方法,清空counter
list(c) # 返回key组成的list
set(c) # 返回key组成的set
dict(c) # 转化成字典
c.items() # 转化成(元素,计数值)组成的列表
Counter(dict(list_of_pairs)) # 从(元素,计数值)组成的列表转化成Counter
c.most_common()[:-n-1:-1] # 最小n个计数的(元素,计数值)组成的列表
c += Counter() # 利用counter的相加来去除负值和0的值
Next
下一篇将从源码层次剖析collection.Counter的实现, 敬请期待啦!
参见这儿: http://www.cnblogs.com/nisen/p/6055980.html
Python Counter()计数工具的更多相关文章
- [python] 使用scikit-learn工具计算文本TF-IDF值
在文本聚类.文本分类或者比较两个文档相似程度过程中,可能会涉及到TF-IDF值的计算.这里主要讲述基于Python的机器学习模块和开源工具:scikit-learn. 希望文章对你有所帮 ...
- Python自然语言处理工具小结
Python自然语言处理工具小结 作者:白宁超 2016年11月21日21:45:26 目录 [Python NLP]干货!详述Python NLTK下如何使用stanford NLP工具包(1) [ ...
- python 包管理工具
python 包管理工具 Python当前的包管理工具链是 easy_install/pip + distribute/setuptools + distutils,显得较为混乱. 而将来的工具链组合 ...
- Python 包管理工具解惑
Python 包管理工具解惑 本文链接:http://zengrong.net/post/2169.htm python packaging 一.困惑 作为一个 Python 初学者,我在包管理上感到 ...
- Python包管理工具介绍
常见的包管理工具及关系 setuptools -->distribute easy_install-->pip 1.distribute distribute是对标准库disutils模块 ...
- python包管理工具
pip 是一个安装和管理 Python 包的工具 , 是 easy_install 的一个替换品.本文将详细说明 安装 pip 的方法和 使用 pip 的一些基本操作如安装.更新和卸载 python ...
- Python学习笔记 (1) :python简介、工具、编码及基础运算
学习背景: 精通一门编程语言并编写出自己喜欢的程序是我多年的梦想,一定要找时间实现.此时想起了高中时的我对编程的兴趣十分浓厚,父母给自己购买了学习机插卡式的,只能敲basic代码,同时学校有386计算 ...
- Python包管理工具和多版本环境管理
1. Python包管理工具 在安装Python包的过程中,经常涉及到distutils.setuptools.distribute.setup.py.easy_install.easy_instal ...
- python的计数引用分析(一)
python的垃圾回收采用的是引用计数机制为主和分代回收机制为辅的结合机制,当对象的引用计数变为0时,对象将被销毁,除了解释器默认创建的对象外.(默认对象的引用计数永远不会变成0) 所有的计数引用+1 ...
随机推荐
- HD2043猜密码
密码 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission ...
- sql的union用法
sql中union是很常见的,尤其是创建视图时,完全离不开union. SQL UNION 操作符合并两个或多个 SELECT 语句的结果,UNION 内部的每个 SELECT 语句必须拥有相同数量的 ...
- hdu 2199 Can you solve this equation?(高精度二分)
http://acm.hdu.edu.cn/howproblem.php?pid=2199 Can you solve this equation? Time Limit: 2000/1000 MS ...
- unigui TUniTreeView demo
unit untTree; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, For ...
- IOS学习之路十二(UITableView下拉刷新页面)
今天做了一个下拉刷新的demo,主要用到了实现的开源框架是:https://github.com/enormego/EGOTableViewPullRefresh 运行结果如下: 实现很简单下载源代码 ...
- pureMVC学习之一
//1var MainWindow: TMainWindow;begin Application.Initialize; Application.MainFormOnTaskbar := Tru ...
- Elasticsearch template configuration
Index templates allow defining templates thatwill automatically be applied to new indices created. T ...
- PHP导出数据库数据字典脚本
<?php /** * mysql数据字典在线生成 * @author change */ //配置数据库 $dbserver = "192.168.1.218:3306"; ...
- OC:copy 与 retain 的区别
copy与retain的区别: copy是创建一个新对象,retain是创建一个指针,引用对象计数加1.Copy属性表示两个对象内容相同,新的对象retain为1 ,与旧有对象的引用计数无关,旧有对象 ...
- ref和out的使用与区别
out的使用 ————————————————————————————————————————————————— class Program { static void Main( ...