Python内置的heapq模块简析

时间:2022-02-19 02:52:42

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方法来实现。

这边先将基本用法罗列出来记录下,下一篇再写稍微复杂场景的程序。