您的位置:首页 > 编程语言 > Python开发

python学习——heapq模块

2015-09-12 16:26 666 查看
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(…)

\qquadTransform list into a heap, in-place, in O(len(heap)) time.

heappop(…)

\qquadPop the smallest item off the heap, maintaining the heap invariant.

heappush(…)

\qquadPush item onto heap, maintaining the heap invariant.

heapreplace(…)

\qquadPop 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:

\qquadif item > heap[0]:

\qquad\qquaditem = heapreplace(heap, item)

nlargest(…)

\qquadFind the n largest elements in a dataset. Equivalent to: sorted(iterable, reverse=True)[:n]

nsmallest(…)

\qquadFind 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: