找到最大或最小的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_64python.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]]
原文地址:https://www.cnblogs.com/dahu-daqing/p/6664607.html