1. 程式人生 > >Python內建的heapq模組簡析

Python內建的heapq模組簡析

Python內建的heapq模組

Python3.4版本中heapq包含了幾個有用的方法:

heapq.heappush(heap,item):將item,推入heap

  1. >>> items = [1,2,9,7,3]

  2. >>> heapq.heappush(items,10)

  3. >>> items

  4. [1, 2, 9, 7, 3, 10]

  5. >>>

  heapq.heappop(heap):將heap的最小值pop出heap,heap為空時報IndexError錯誤

  1. >>> heapq.heappop(items)#heap在pop時總是將最小值首先pop出

  2. 1

  3. >>> items

  4. [2, 3, 9, 7, 10]

  5. >>>

  heapq.heappushpop(heap,item):pop出heap中最小的元素,推入item

  1. >>> items

  2. [2, 3, 9, 7, 10]

  3. >>> heapq.heappushpop(items,11)

  4. 2

  5. >>> items

  6. [3, 7, 9, 11, 10]

  7. >>>

heapq.heapify(x):將list X轉換為heap

  1. >>> nums = [1,10,9,8]

  2. >>> heap = list(nums)

  3. >>> heapq.heapify(heap)

  4. >>> heap

  5. [1, 8, 9, 10]

  6. >>>

  heapq.heapreplace(heap,item):pop出最小值,推入item,heap的size不變

  1. >>> heap

  2. [1, 8, 9, 10]

  3. >>> heapq.heapreplace(heap,100)

  4. 1

  5. >>> heap

  6. [8, 10, 9, 100]

  7. >>

heapq.merge(*iterable):將多個可迭代合併,並且排好序,返回一個iterator

  1. >>> heap

  2. [8, 10, 9, 100]

  3. >>> heap1 = [10,67,56,80,79]

  4. >>> h = heapq.merge(heap,heap1)

  5. >>> list(h)

  6. [8, 10, 9, 10, 67, 56, 80, 79, 100]#需要 說明的是這裡所謂的排序不是完全排序,只是兩個list對應位置比較,

  7. #將小的值先push,然後大的值再與另外一個list的下一個值比較

heapq.nlargest(n,iterable,key):返回item中大到小順序的前N個元素,key預設為空,可以用來指定規則如:function等來處理特定的排序

  1. itemsDict=[

  2. {'name':'dgb1','age':23,'salary':10000},

  3. {'name':'dgb2','age':23,'salary':15000},

  4. {'name':'dgb3','age':23,'salary':80000},

  5. {'name':'dgb4','age':23,'salary':80000}

  6. ]

  7. itemsDictlarge = heapq.nlargest(3,itemsDict,lambda s:s['salary'])

  8. print(itemsDictlarge)

  9. [{'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方法來實現。

這邊先將基本用法羅列出來記錄下,下一篇再寫稍微複雜場景的程式。