查找最大或最小的 N 個元素

使用內置的heapd模塊

In [1]: import heapq

In [2]: nums = [1,8, 2, 23, 7, -4, 18, 23, 42, 37, 2]

In [3]: print(heapq.nlargest(2,nums))
[42, 37]

In [4]: print(heapq.nlargest(5,nums))
[42, 37, 23, 23, 18]

In [5]: print(heapq.nsmallest(5,nums))
[-4, 1, 2, 2, 7]

兩個函數都能接受一個關鍵字參數,用於更復雜的數據結構中

In [6]: 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}
   ...: ]
In [11]: print(heapq.nsmallest(3,portfolio,key=lambda s: s['price']))
[{'price': 16.35, 'name': 'YHOO', 'shares': 45}, {'price': 21.09, 'name': 'FB', 'shares': 200}, {'price': 31.75, 'name': 'HPQ', 'shares': 35}]

In [12]: print(heapq.nsmallest(2,portfolio,key=lambda s: s['price']))
[{'price': 16.35, 'name': 'YHOO', 'shares': 45}, {'price': 21.09, 'name': 'FB', 'shares': 200}]

那麼若是你想在集合中找到最小和最大的值

由於在底層實現裏面,首先會先將集合數據進行堆排序後放入一個列表中api

In [1]: import heapq

In [2]: nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2
   ...: ]

In [3]: heap=list(nums)

In [4]: heap
Out[4]: [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]

In [5]: heapq.heapify(heap)

In [6]: heap
Out[6]: [-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]

In [7]: heap[0]
Out[7]: -4

In [8]: heapq.heappop(heap)
Out[8]: -4

In [9]: heapq.heappop(heap)
Out[9]: 1

In [10]: heapq.heappop(heap)
Out[10]: 2

In [11]: heapq.heappop(heap)
Out[11]: 2

In [12]: heapq.heappop(heap)
Out[12]: 7

In [13]: heap
Out[13]: [8, 23, 18, 23, 42, 37]

堆數據結構最重要的特徵是 heap[0] 永遠是最小的元素。而且剩餘的元素能夠很容易的經過調用heapq.heappop() 方法獲得, 該方法會先將第一個元素彈出來,而後用下一個最小的元素來取代被彈出元素(這種操做時間複雜度僅僅是 O(log N),N 是堆大小數據結構

當要查找的元素個數相對比較小的時候,函數 nlargest() 和 nsmallest() 是很合適的。 若是你僅僅想查找惟一的最小或最大(N=1)的元素的話,那麼使用 min() 和 max() 函數會更快些。 相似的,若是 N 的大小和集合大小接近的時候,一般先排序這個集合而後再使用切片操做會更快點 ( sorted(items)[:N] 或者是 sorted(items)[-N:] )。 須要在正確場合使用函數 nlargest() 和 nsmallest() 才能發揮它們的優點 (若是 N 快接近集合大小了,那麼使用排序操做會更好些)。
相關文章
相關標籤/搜索