Python內建的heapq模組簡析
Python內建的heapq模組
Python3.4版本中heapq包含了幾個有用的方法:
heapq.heappush(heap,item):將item,推入heap
-
>>> items = [1,2,9,7,3]
-
>>> heapq.heappush(items,10)
-
>>> items
-
[1, 2, 9, 7, 3, 10]
-
>>>
heapq.heappop(heap):將heap的最小值pop出heap,heap為空時報IndexError錯誤
-
>>> heapq.heappop(items)#heap在pop時總是將最小值首先pop出
-
1
-
>>> items
-
[2, 3, 9, 7, 10]
-
>>>
heapq.heappushpop(heap,item):pop出heap中最小的元素,推入item
-
>>> items
-
[2, 3, 9, 7, 10]
-
>>> heapq.heappushpop(items,11)
-
2
-
>>> items
-
[3, 7, 9, 11, 10]
-
>>>
heapq.heapify(x):將list X轉換為heap
-
>>> nums = [1,10,9,8]
-
>>> heap = list(nums)
-
>>> heapq.heapify(heap)
-
>>> heap
-
[1, 8, 9, 10]
-
>>>
heapq.heapreplace(heap,item):pop出最小值,推入item,heap的size不變
-
>>> heap
-
[1, 8, 9, 10]
-
>>> heapq.heapreplace(heap,100)
-
1
-
>>> heap
-
[8, 10, 9, 100]
-
>>
heapq.merge(*iterable):將多個可迭代合併,並且排好序,返回一個iterator
-
>>> heap
-
[8, 10, 9, 100]
-
>>> heap1 = [10,67,56,80,79]
-
>>> h = heapq.merge(heap,heap1)
-
>>> list(h)
-
[8, 10, 9, 10, 67, 56, 80, 79, 100]#需要 說明的是這裡所謂的排序不是完全排序,只是兩個list對應位置比較,
-
#將小的值先push,然後大的值再與另外一個list的下一個值比較
heapq.nlargest(n,iterable,key):返回item中大到小順序的前N個元素,key預設為空,可以用來指定規則如:function等來處理特定的排序
-
itemsDict=[
-
{'name':'dgb1','age':23,'salary':10000},
-
{'name':'dgb2','age':23,'salary':15000},
-
{'name':'dgb3','age':23,'salary':80000},
-
{'name':'dgb4','age':23,'salary':80000}
-
]
-
itemsDictlarge = heapq.nlargest(3,itemsDict,lambda s:s['salary'])
-
print(itemsDictlarge)
-
[{'name': 'dgb3', 'age': 23, 'salary': 80000}, {'name': 'dgb4', 'age': 23, 'salary': 80000}, {'name': 'dgb2', 'age': 23, 'salary': 15000}]
如果沒有指定key,那麼就按照第一個欄位來排序
heapq.nsmallest(n,iterable,key):返回item中小到大順序的前N個元素,key預設為空,可以用來指定規則如:function等來處理特定的排序
這個函式的用法與上一個nlargest是一樣的。
To create a heap, use a list initialized to[], or you can transform a populated list into a heap via functionheapify().
建立heap可以通過建立list,和使用heapify方法來實現。
這邊先將基本用法羅列出來記錄下,下一篇再寫稍微複雜場景的程式。