1. 程式人生 > 實用技巧 >【python】詳解python資料結構堆(heapq)庫使用

【python】詳解python資料結構堆(heapq)庫使用

資料結構堆(heap)是一種優先佇列。使用優先佇列能夠以任意順序增加物件,並且能在任意的時間(可能在增加物件的同時)找到(也可能移除)最小的元素,也就是說它比python的min方法更加有效率。

1、heappush(heap,n)資料堆入

In [1]: import heapq as hq
In [2]: import numpy as np
In [3]: data = np.arange(10)
#將生成的資料隨機打亂順序
In [4]: np.random.shuffle(data)
In [5]: data
Out[5]: array([5, 8, 6, 3, 4, 7, 0, 1, 2, 9])
#定義heap列表
In [6]: heap = []
#使用heapq庫的heappush函式將資料堆入
In [7]: for i in data:
   ...:     hq.heappush(heap,i)
   ...:
In [8]: heap
Out[8]: [0, 1, 3, 2, 5, 7, 6, 8, 4, 9]

In [9]: hq.heappush(heap,0.5)
In [10]: heap
Out[10]: [0, 0.5, 3, 2, 1, 7, 6, 8, 4, 9, 5]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

2、heappop(heap)將陣列堆中的最小元素彈出

In [11]: hq.heappop(heap)
Out[11]: 0

In [12]: hq.heappop(heap)
Out[12]: 0.5
  • 1
  • 2
  • 3
  • 4
  • 5

3、heapify(heap) 將heap屬性強制應用到任意一個列表

heapify 函式將使用任意列表作為引數,並且儘可能少的移位操作,,將其轉化為合法的堆。如果沒有建立堆,那麼在使用heappush和heappop前應該使用該函式。

In [13]: heap = [5,8,0,3,6,7,9,1,4,2]

In [14]: hq.heapify(heap)

In [15]: heap
Out[15]: [0, 1, 5, 3, 2, 7, 9, 8, 4, 6]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

4、heapreplace(heap,n)彈出最小的元素被n替代

In [17]: hq.heapreplace(heap,0.5)
Out[17]: 0

In [18]: heap
Out[18]: [0.5, 1, 5, 3, 2, 7, 9, 8, 4, 6]
  • 1
  • 2
  • 3
  • 4
  • 5

5、nlargest(n,iter)、nsmallest(n,iter)
heapq中剩下的兩個函式nlargest(n.iter)和nsmallest(n.iter)分別用來尋找任何可迭代的物件iter中第n大或者第n小的元素。可以通過使用排序(sorted函式)和分片進行完成。

#返回第一個最大的數
In [19]: hq.nlargest(1,heap)
Out[19]: [9]
#返回第一個最小的數
In [20]: hq.nsmallest(1,heap)
Out[20]: [0.5]