详解python之heapq模块及排序操作


Posted in Python onApril 04, 2019

说到排序,很多人可能第一想到的就是sorted,但是你可能不知道python中其实还有还就中方法哟,并且好多种场景下效率都会比sorted高。那么接下来我就依次来介绍我所知道的排序操作。

sorted(iterable, *, key=None, reverse=False)

list1=[1,6,4,3,9,5]
list2=['12','a6','4','c34','b9','5']

print(sorted(list1)) #[1, 3, 4, 5, 6, 9]
print(sorted(list2)) #['12', '4', '5', 'a6', 'b9', 'c34']
#总结上面两种排序:字符串排序根据元素首字符的ASCII比较进行排序,
#数字类型按照大小排序,数字不能混合排序

list3=[
 {'name':'jim','age':23,'price':500},
 {'name':'mase','age':23,'price':600},
 {'name':'tom','age':25,'price':2000},
 {'name':'alice','age':22,'price':300},
 {'name':'rose','age':21,'price':2400},
]

print(sorted(list3,key=lambda s:(s['age'],s['price'])))
#[{'name': 'rose', 'age': 21, 'price': 2400}, {'name': 'alice', 'age': 22, 'price': 300}, {'name': 'jim', 'age': 23, 'price': 500}, {'name': 'mase', 'age': 23, 'price': 600}, {'name': 'tom', 'age': 25, 'price': 2000}]

最后的reverse参数我就不作说明了,就是把结果进行倒序,可用作降序排列
介绍一种比lambda效率高的方式:
operator模块中的方法itemgetter
>>> itemgetter(1)('ABCDEFG')
'B'
>>> itemgetter(1,3,5)('ABCDEFG')
('B', 'D', 'F')
>>> itemgetter(slice(2,None))('ABCDEFG')
'CDEFG
运用到上述代码
print(sorted(list3,key=itemgetter('age','price'))) #结果同上但效率会比较高

接下来的排序操作涉及到一个非常重要的一种数据结构——堆,不过今天我主要介绍这个模块中的方法,具体什么是堆,及其还有一种数据结构——栈,有时间我会专门写一篇文章来介绍。

heapq(Python内置的模块)

__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge',
           'nlargest', 'nsmallest', 'heappushpop']

接下来我们一一介绍。

nlargest与nsmallest,通过字面意思可以看出方法大致的作用,接下来动手测验

nlargest(n, iterable, key=None)
nsmallest(n, iterable, key=None)
#n:查找个数 iterable:可迭代对象 key:同sorted

list1=[1,6,4,3,9,5]
list2=['12','a6','4','c34','b9','5']
list3=[
 {'name':'jim','age':23,'price':500},
 {'name':'mase','age':23,'price':600},
 {'name':'tom','age':25,'price':2000},
 {'name':'alice','age':22,'price':300},
 {'name':'rose','age':21,'price':2400},
]

from operator import itemgetter
import heapq

print(heapq.nlargest(len(list1),list1))
print(heapq.nlargest(len(list2),list2))
print(heapq.nlargest(len(list3),list3,key=itemgetter('age','price')))
#以上代码输出结果同sorted

print(heapq.nsmallest(len(list1),list1))
print(heapq.nsmallest(len(list2),list2))
print(heapq.nsmallest(len(list3),list3,key=itemgetter('age','price')))
#结果是降序
[1, 3, 4, 5, 6, 9]
['12', '4', '5', 'a6', 'b9', 'c34']
[{'name': 'rose', 'age': 21, 'price': 2400}, {'name': 'alice', 'age': 22, 'price': 300}, {'name': 'jim', 'age': 23, 'price': 500}, {'name': 'mase', 'age': 23, 'price': 600}, {'name': 'tom', 'age': 25, 'price': 2000}]

heappush,heappop,heapify,heapreplace,heappushpop

堆结构特点:heap[0]永远是最小的元素(利用此特性排序)

heapify:对序列进行堆排序,
heappush:在堆序列中添加值
heappop:删除最小值并返回
heappushpop:添加并删除堆中最小值且返回,添加之后删除
heapreplace:添加并删除队中最小值且返回,删除之后添加

nums=[54,23,64.,323,53,3,212,453,65]
heapify(nums)  #先进行堆排序
print(heappop(nums))  #3
print(heappush(nums,50))  #添加操作,返回None
print(heappushpop(nums,10))  #由于是添加后删除,所以返回10
print(heappop(nums))  #23
print(heapreplace(nums,10))  #和heappushpop,返回50
print(nums)  #[10, 53, 54, 65, 323, 64.0, 212, 453]

merge:合并多个序列

list1 = [1, 2, 3, 4, 5, 12]
set1 = {2, 3, 9, 23, 54}
s = list(merge(list1,set1))
print(s)  #[1, 2, 2, 3, 3, 4, 5, 9, 12, 54, 23]
#发现输出结果不仅进行了合并,还进行了排序,有意思哈,可是换个代码测验,你再看一下

list1 = [31, 2, 83, 24, 5, 12]
set1 = {2, 83, 9, 23, 54}
s = list(merge(list1,set1))
print(s)  #[2, 9, 31, 2, 83, 24, 5, 12, 83, 54, 23]
#你们肯定想这是什么鬼,一点都没有头绪,其实经过我的多次测验,还是有规律的,但是由于没有什么作用就不大篇幅说明了,喜欢刨根问题的小伙伴可以尝试自己思考一下。

小伙伴们有没有想我为何介绍这个模块,并且和排序放在一起呢,其实在很多时候我们需要找序列中的前几个最大值或者最小值,使用此模块中的方法是最好不过的了。

如果需要全部排序我们使用sorted,需要查找最大或最小的几个或者多个我们使用alargest/asmallest,查找最大最小使用max/min

Python 相关文章推荐
python fabric实现远程操作和部署示例
Mar 25 Python
python中import reload __import__的区别详解
Oct 16 Python
5款Python程序员高频使用开发工具推荐
Apr 10 Python
Django框架验证码用法实例分析
May 10 Python
python图形工具turtle绘制国际象棋棋盘
May 23 Python
详解Python绘图Turtle库
Oct 12 Python
Pytorch 实现focal_loss 多类别和二分类示例
Jan 14 Python
python使用html2text库实现从HTML转markdown的方法详解
Feb 21 Python
浅析python 动态库m.so.1.0错误问题
May 09 Python
python实现简单反弹球游戏
Apr 12 Python
浅析Python实现DFA算法
Jun 26 Python
一篇文章搞懂python混乱的切换操作与优雅的推导式
Aug 23 Python
python实现kmp算法的实例代码
Apr 03 #Python
详解python多线程之间的同步(一)
Apr 03 #Python
Python将列表数据写入文件(txt, csv,excel)
Apr 03 #Python
详解python读取image
Apr 03 #Python
Python小白必备的8个最常用的内置函数(推荐)
Apr 03 #Python
查看python安装路径及pip安装的包列表及路径
Apr 03 #Python
元组列表字典(莫烦python基础)
Apr 03 #Python
You might like
php 图片上添加透明度渐变的效果
2009/06/29 PHP
php一些错误处理的方法与技巧总结
2013/08/10 PHP
php中的动态调用实例分析
2015/01/07 PHP
Centos 6.5下PHP 5.3安装ffmpeg扩展的步骤详解
2017/03/02 PHP
php简单实现单态设计模式的方法分析
2017/07/28 PHP
Laravel使用支付宝进行支付的示例代码
2017/08/16 PHP
Yii框架学习笔记之应用组件操作示例
2019/11/13 PHP
Alliance vs Liquid BO3 第三场2.13
2021/03/10 DOTA
破除网页鼠标右键被禁用的绝招大全
2006/12/27 Javascript
JavaScript 动态将数字金额转化为中文大写金额
2009/05/14 Javascript
实现png图片和png背景透明(支持多浏览器)的方法
2009/09/08 Javascript
JavaScript 自动分号插入(JavaScript synat:auto semicolon insertion)
2009/11/04 Javascript
javascript学习笔记(九)javascript中的原型(prototype)及原型链的继承方式
2011/04/12 Javascript
原生js实现给指定元素的后面追加内容
2013/04/10 Javascript
JS动态显示表格上下frame的方法
2015/03/31 Javascript
jQuery实现手机版页面翻页效果的简单实例
2016/10/05 Javascript
用React实现一个完整的TodoList的示例代码
2017/10/30 Javascript
node实现登录图片验证码的示例代码
2018/04/20 Javascript
vue 引用自定义ttf、otf、在线字体的方法
2019/05/09 Javascript
JS浏览器BOM常见操作实例详解
2020/04/27 Javascript
在Vue中使用Viser说明(基于AntV-G2可视化引擎)
2020/10/28 Javascript
[00:10]DOTA2全国高校联赛 以DOTA2会友
2018/05/30 DOTA
Python中的exec、eval使用实例
2014/09/23 Python
一百多行python代码实现抢票助手
2018/09/25 Python
pybind11在Windows下的使用教程
2019/07/04 Python
Pytorch .pth权重文件的使用解析
2020/02/14 Python
Python爬虫程序架构和运行流程原理解析
2020/03/09 Python
全球领先的鞋类零售商:The Walking Company
2016/07/21 全球购物
Napapijri西班牙在线商店:夹克、外套、运动衫等
2020/11/05 全球购物
产品质量承诺书
2014/03/27 职场文书
单位工作证明范文
2014/09/14 职场文书
机械专业毕业生自我鉴定2014
2014/10/04 职场文书
学校领导四风问题整改措施思想汇报
2014/10/09 职场文书
大学生见习报告总结
2014/11/04 职场文书
如何才能写好调研报告?
2019/07/03 职场文书
如何使用flask将模型部署为服务
2021/05/13 Python