赞
踩
heapq
模块是Python标准库中的一个模块,提供了对堆(heap)数据结构的支持。
heapq
模块提供了一系列函数来操作堆,包括:
heappush(heap, item)
:将元素item
添加到堆heap
中。heappop(heap)
:从堆heap
中弹出并返回最小(或最大)的元素。heapify(heap)
:将列表heap
原地转换为一个合法的堆。heapreplace(heap, item)
:将堆heap
中的最小(或最大)元素弹出,并将元素item
添加到堆中。heappushpop(heap, item)
:将元素item
添加到堆heap
中,并返回堆中的最小(或最大)元素。nlargest(k, iterable)
:返回可迭代对象iterable
中最大的k
个元素。nsmallest(k, iterable)
:返回可迭代对象iterable
中最小的k
个元素。以下是一个使用heapq
模块的示例代码,演示了如何创建一个最小堆并进行基本操作:
- import heapq
-
- # 创建一个空的堆
- heap = []
-
- # 添加元素到堆中
- heapq.heappush(heap, 5)
- heapq.heappush(heap, 3)
- heapq.heappush(heap, 7)
- heapq.heappush(heap, 1)
-
- # 弹出并打印堆中的最小元素
- print(heapq.heappop(heap)) # 输出: 1
-
- # 将列表转换为堆
- heap = [5, 3, 7, 1]
- heapq.heapify(heap)
-
- # 弹出并打印堆中的最小元素
- print(heapq.heappop(heap)) # 输出: 1

输出结果为:
- 1
- 1
参考:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。