堆排序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
列出一些常見的用法:
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]]