找到最大或最小的N个元素---heapq模块

堆排序heapq的用法

基本用法:

复杂数据结构:

复制代码
# coding=utf-8
# example.py
# Example of using heapq to find the N smallest or largest items
import heapq portfolio
= [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65} ] cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price']) #对price进行排序 expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price']) print(cheap) print(expensive)
复制代码

输出结果:

复制代码
H:\Python27_64\python.exe H:/myfile/python-cookbook-master/src/1/finding_the_largest_or_smallest_n_items/example.py
[{'price': 16.35, 'name': 'YHOO', 'shares': 45}, {'price': 21.09, 'name': 'FB', 'shares': 200}, {'price': 31.75, 'name': 'HPQ', 'shares': 35}]
[{'price': 543.22, 'name': 'AAPL', 'shares': 50}, {'price': 115.65, 'name': 'ACME', 'shares': 75}, {'price': 91.1, 'name': 'IBM', 'shares': 100}]

进程已结束,退出代码0
View Code
复制代码

列出一些常见的用法:

heap = []#建立一个常见的堆

heappush(heap,item)#往堆中插入一条新的值

item = heappop(heap)#弹出最小的值

item = heap[0]#查看堆中最小的值,不弹出

heapify(x)#以线性时间将一个列表转为堆

item = heapreplace(heap,item)#弹出一个最小的值,然后将item插入到堆当中。堆的整体的结构不会发生改变。
heappoppush()#弹出最小的值,并且将新的值插入其中

merge()#将多个堆进行合并

nlargest(n , iterbale, key=None)从堆中找出做大的N个数,key的作用和sorted( )方法里面的key类似,用列表元素的某个属性和函数作为关键字

实验:

复制代码
a=range(9,0,-2)
print a
[9, 7, 5, 3, 1]
print heapq.nlargest(3,a)
[9, 7, 5]
heapq.heapify(a)
print a,a[0]
[1, 3, 5, 9, 7] 1
print heapq.heappop(a),heapq.heappop(a)
1 3
print a,'>>>'
[5, 7, 9] >>>
heapq.heappush(a,8)      #直接放在堆的最后
print a
[5, 7, 9, 8]
heapq.heapreplace(a,7.5)    #删一个左边的,item插进去
print a
[7, 7.5, 9, 8]
heapq.heappushpop(a,8.5)    #删一个左边的,item插最后
print a
[7.5, 8, 9, 8.5]
a.sort()
print a
[7.5, 8, 8.5, 9]
print a[3]
9
复制代码
#多个堆进行合并

复制代码
b=range(3,6)
heapq.heapify(b)
c=range(13,16)
c.append([17,18])
print c
[13, 14, 15, [17, 18]]

heapq.heapify(c)
print c
[13, 14, 15, [17, 18]]

print list(heapq.merge(b,c))    
[
3, 4, 5, 13, 14, 15, [17, 18]]
复制代码

 

posted @   dahu1  Views(2341)  Comments(0Edit  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示