heapq是python中包含堆的相关操作的模块,其典型的应用就是取top K个数:
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]
print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]
对于其它的数据类型可以如下操作:
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'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
heapify(…)
Transform list into a heap, in-place, in O(len(heap)) time.
heappop(…)
Pop the smallest item off the heap, maintaining the heap invariant.
heappush(…)
Push item onto heap, maintaining the heap invariant.
heapreplace(…)
Pop and return the current smallest value, and add the new item. This is more efficient than heappop() followed by heappush(), and can be more appropriate when using a fixed-size heap. Note that the value returned may be larger than item! That constrains reasonable uses of this routine unless written as part of a conditional replacement:
if item > heap[0]:
item = heapreplace(heap, item)
nlargest(…)
Find the n largest elements in a dataset. Equivalent to: sorted(iterable, reverse=True)[:n]
nsmallest(…)
Find the n smallest elements in a dataset.
>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
>>> import heapq
>>> heap = list(nums)
>>> heapq.heapify(heap)
>>> heap
[-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]
>>> heapq.heappop(heap)
-4
>>> heapq.heappop(heap)
1
>>> heapq.heappop(heap)
2