heapq模块常见操作python代码
时间: 2023-07-26 19:36:56 浏览: 154
以下是 `heapq` 模块中常见的操作和对应的 Python 代码示例:
1. 将列表转化为堆:`heapq.heapify(lst)`
```python
import heapq
lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
heapq.heapify(lst)
print(lst) # 输出 [1, 1, 2, 3, 3, 9, 4, 6, 5, 5, 5]
```
2. 从堆中弹出最小的元素:`heapq.heappop(heap)`
```python
import heapq
heap = [1, 3, 2, 6, 4, 8, 5, 7, 9]
min_element = heapq.heappop(heap)
print(min_element) # 输出 1
```
3. 将元素加入堆中:`heapq.heappush(heap, item)`
```python
import heapq
heap = [1, 3, 2, 6, 4, 8, 5, 7, 9]
heapq.heappush(heap, 0)
print(heap) # 输出 [0, 1, 2, 6, 3, 8, 5, 7, 9, 4]
```
4. 获取堆中最小的元素,但不弹出:`heapq.nsmallest(n, heap)`
```python
import heapq
heap = [1, 3, 2, 6, 4, 8, 5, 7, 9]
smallest_3 = heapq.nsmallest(3, heap)
print(smallest_3) # 输出 [1, 2, 3]
```
5. 获取堆中最大的元素,但不弹出:`heapq.nlargest(n, heap)`
```python
import heapq
heap = [1, 3, 2, 6, 4, 8, 5, 7, 9]
largest_3 = heapq.nlargest(3, heap)
print(largest_3) # 输出 [9, 8, 7]
```
阅读全文