Python Counter()计数工具
来源:互联网 发布:cf易语言源码大全 编辑:程序博客网 时间:2024/06/15 05:55
collections.Counter([iterable-or-mapping])用于统计各元素的计数,结果为map,可选的参数为迭代对象或字典map。
>>> c2=Counter('banana') #创建字符串的Counter对象>>> c2Counter({'a': 3, 'n': 2, 'b': 1})>>> c2=Counter({'a':2,'b':3}) >>> c2Counter({'b': 3, 'a': 2})>>> c3=Counter(a=3,b=5) #创建关键字参数的Counter对象>>> c3Counter({'b': 5, 'a': 3})>>> c3['b'] #访问Counter对象的键5>>> c3['aa'] #如果键值不存在,返回00>>> c3.elements #返回列表元素<bound method Counter.elements of Counter({'b': 5, 'a': 3})> most_common(n) #返回计数值中最大的n个元素的元组>>> c1.most_common(5)[('asdf', 6), ('asd', 5), ('sadf', 3), ('df', 3), ('aa', 3)]# 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)>>> cCounter({'a': 3, 'b': 0, 'c': -3, 'd': -6})# update([iterable-or-mapping]) 不同于字典的update方法,这里更新counter时,相同的key的value值相加而不是覆盖# 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相减,只保留正值得valueCounter({'c': 5, 'a': 2})>>> c & d # 交集: 取两者都有的key,value取小的那一个Counter({'a': 1, 'b': 1})>>> c | d # 并集: 汇聚所有的key, key相同的情况下,取大的valueCounter({'c': 5, 'd': 4, 'a': 3, 'b': 2})常见做法:sum(c.values()) # 继承自字典的.values()方法返回values的列表,再求和c.clear() # 继承自字典的.clear()方法,清空counterlist(c) # 返回key组成的listset(c) # 返回key组成的setdict(c) # 转化成字典c.items() # 转化成(元素,计数值)组成的列表Counter(dict(list_of_pairs)) # 从(元素,计数值)组成的列表转化成Counterc.most_common()[:-n-1:-1] # 最小n个计数的(元素,计数值)组成的列表c += Counter() # 利用counter的相加来去除负值和0的值
举个计数的例子,需要统计一个文件中,每个单词出现的次数。实现方法如下:
from collections import *import rewith open('test.txt') as f: words=re.findall(r'\w+',f.read().lower()) c=Counter(words) print(c)
阅读全文
0 0
- Python Counter()计数工具
- Python Counter()计数工具
- python学习:counter计数
- python-Counter计数函数
- Python中Counter计数统计
- python使用Collections.Counter进行计数
- python学习——Counter计数方法
- SAE云应用Counter工具实现访问计数
- Python:使用Counter进行计数统计及collections模块
- python Counter
- 计数时使用Counter计数对象
- Python使用collections的Counter类对字符串、列表、字典的数据元素进行计数
- enumerate Counter in python
- Python Collections Counter
- Python Counter() 的实现
- python collections Counter
- python Counter模块
- python中counter()记数
- 6.18
- Hybrid APP的离线存储总结
- HTTP小常识
- GitLab使用总结
- 传感器
- Python Counter()计数工具
- 计算一个三位数各位数之和
- 机器学习--决策树和随机森林简介
- 链表(作业二)
- android 之OkHttp封装模板
- matrix67系列好文
- python可以玩的海龟(turtle)画图软件
- 软件工程(C编码实践篇)学习总结
- 热键