目录
1.heapq.heapify(list)
2.heapq.heappush(heap,item)
3.heapq.heappop(heap)
4.heapq.nlargest(n,heap)
5.heap.nsmallest(n,heap)
6.heapq.heapreplace(heap,item)
7.heapq.heappushpop(heap,item)
heapq库中的堆默认为最小堆,即heap[0]为最小的对象
堆采用的是先序遍历方式变成list类型
作用:将list用最小堆的方式重新排序。
import heapq lst1 = [3,2,3,4] heapq.heapify(lst1) print(lst1,type(lst1))
结果:
[2, 3, 3, 4]
2.heapq.heappush(heap,item)
作用:将item添加到heap堆中。
lst1 = [3,2,3,4,5,6,7]
heapq.heappush(lst1,2)
print(lst1,type(lst1))
结果:
[3, 2, 3, 2, 5, 6, 7, 4]
作用:将heap堆中输出第一项,也就是输出最小项。
lst1 = [3,2,3,4,5,6,7]
a = heapq.heappop(lst1)
print(a)
print(lst1,type(lst1))
结果:
3
[2, 4, 3, 7, 5, 6]
作用:返回值是个list类型,list是从heap中从大到小查找n个放入列表的。
lst1 = [3,2,3,4,5,6,7]
print(heapq.nlargest(3,lst1))
结果:
[7, 6, 5]
作用:返回值是个list类型,list是从heap中从小到大查找n个放入列表的。
lst1 = [3,2,3,4,5,6,7]
print(heapq.nsmallest(3,lst1))
结果:
[2, 3, 3]
作用:item去替代heap中的第一个元素,被替代的元素作为返回值,heap按最小堆排序。
lst1 = [3,2,3,4,5,6,7]
b = heapq.heapreplace(lst1,1)
print(b)
print(lst1,type(lst1))
结果:
3
[1, 2, 3, 4, 5, 6, 7]
作用:先将item添加到heap中,再将添加后的heap堆中的第一个元素返回并删除。
lst1 = [3,2,3,4,5,6,7]
a = heapq.heappushpop(lst1,5)
print(a,lst1)
b = heapq.heappushpop(lst1,1)
print(b,lst1)
结果:
3 [2, 4, 3, 5, 5, 6, 7]
1 [2, 4, 3, 5, 5, 6, 7]