Python中对序列数据的汇总(collections模块)
2023-09-11 14:14:04 时间
目录
对于序列如字符串str、列表list和tuple可以统计里面数据出现的次数。我们使用的是 collections 模块。
collections模块的常用方法有:
- 计数器(Counter)
- 双向队列(deque)
- 默认字典(defaultdict)
- 有序字典(OrderedDict)
- 可命名元组(namedtuple)
使用以上类型时需要导入模块 from collections import *
Counter
Counter()方法对传入的序列中出现的数据进行汇总,返回一个<class 'collections.Counter'>的对象
from collections import Counter
a="aabcac"
b=['a','a','b','c','a','c']
c=('a','a','b','c','a','c')
print(Counter(a),type(Counter(a)))
print(Counter(b))
print(Counter(c))
#######################################
Counter({'a': 3, 'c': 2, 'b': 1}) <class 'collections.Counter'>
Counter({'a': 3, 'c': 2, 'b': 1})
Counter({'a': 3, 'c': 2, 'b': 1})
most_common
most_common方法对Counter()汇总的数据进行从高到低的排序,返回前 n 个元素的字典,返回的是列表型的数据
from collections import Counter
a="aabcac"
b=['a','a','b','c','a','c']
c=('a','a','b','c','a','c')
print(Counter(a))
print(Counter(b))
print(Counter(c))
print(Counter(a).most_common(3),type(Counter(a).most_common(3)))
print(Counter(b).most_common(2))
print(Counter(c).most_common(1))
##############################################
Counter({'a': 3, 'c': 2, 'b': 1})
Counter({'a': 3, 'c': 2, 'b': 1})
Counter({'a': 3, 'c': 2, 'b': 1})
[('a', 3), ('c', 2), ('b', 1)] <class 'list'>
[('a', 3), ('c', 2)]
[('a', 3)]
相关文章
- 小白学 Python 数据分析(2):Pandas (一)概述
- 【Python】python对象与json相互转换
- 【python cookbook】【数据结构与算法】16.筛选序列中的元素
- Python 库pyautogui 0.9.52的下载、安装和使用
- 华为OD机试 - 最多等和不相交连续子序列(Java & JS & Python)
- 华为OD机试 - 欢乐的周末(Java & JS & Python)
- Python之多线程:python多线程设计之同时执行多个函数命令详细攻略
- Python语言学习:Python语言学习之python包/库package的简介(模块的封装/模块路径搜索/模块导入方法/自定义导入模块实现华氏-摄氏温度转换案例应用)、使用方法、管理工具之详细攻略
- Python编程语言学习:python中浅复制/深复制(或浅拷贝/深拷贝)的简介、案例应用注意事项之详细攻略
- Python编程语言学习:包导入和模块搜索路径(包路径)简介、使用方法(python系统环境路径的查询与添加)之详细攻略
- Python之tkinter:动态演示调用python库的tkinter带你进入GUI世界(text.insert/link各种事件)
- Python语言学习:利用python语言实现调用内部命令(python调用Shell脚本)—命令提示符cmd的几种方法
- python --> Python初阶 --> 基础语法 --> 条件和分支
- 《看漫画学Python》1、2版分享,python最佳入门教程,中学生用业余时间都能学会,北大教授看完都这样定义它
- 〖Python WEB 自动化测试实战篇③〗- python-selenium环境配置搭建
- 〖Python自动化办公篇⑳〗 - python实现邮件自动化 - 发送html邮件和带附件的邮件
- 【Python成长之路】python 基础篇 -- 装饰器【华为云分享】
- Python时间序列之calendar模块
- Python编程:查看python环境支持的whl
- Python编程:python中的计时器timeit模块
- Python爬虫:常用的浏览器请求头User-Agent
- Python编程:uWSGI+nginx配置flask实例
- python glob 模块
- Python使用技巧(五):快速解决安装python-lxml模块库报错问题并简单使用
- 求一个集合的所有子集 Python实现
- python学习===如何理解python中的return
- python零基础学编程:Python是什么?为什么Python这么火,学Python能干什么?
- Python .py 文件打包成 .exe 文件(Windows平台,python 3.x)