当前位置:   article > 正文

【随手记】python的heapq库的基本用法

heapq库

每次用都要问AI,干脆记录一下,多用就熟了。

Python的heapq库是用于实现堆(优先队列)算法的库。它提供了一些函数来操作堆结构,如push、pop、heapify等。

下面是一些heapq库常用函数的说明:

  1. heapq.heappush(heap, item):将元素item推入堆heap中。
  2. heapq.heappop(heap):从堆heap中弹出并返回最小的元素。
  3. heapq.heapify(heap):将列表heap原地转换为一个堆。
  4. heapq.heappushpop(heap, item):将元素item推入堆heap,并弹出并返回堆中最小的元素。
  5. heapq.heapreplace(heap, item):弹出并返回堆heap中最小的元素,然后将元素item推入堆中。
  6. heapq.nsmallest(n, iterable):返回可迭代对象iterable中最小的n个元素。
  7. heapq.nlargest(n, iterable):返回可迭代对象iterable中最大的n个元素。

下面是一个示例代码,演示了如何使用heapq来操作堆:

import heapq

# 创建一个空堆
heap = []

# 向堆中添加元素
heapq.heappush(heap, 5)
heapq.heappush(heap, 2)
heapq.heappush(heap, 7)
heapq.heappush(heap, 3)

# 从堆中弹出并返回最小的元素
smallest = heapq.heappop(heap)
print(smallest)  # 输出: 2

# 将列表转换为堆
nums = [6, 1, 9, 4, 8]
heapq.heapify(nums)
print(nums)  # 输出: [1, 4, 6, 9, 8]

# 弹出并返回堆中最小的元素,然后将元素9推入堆中
smallest = heapq.heapreplace(nums, 9)
print(smallest)  # 输出: 1
print(nums)  # 输出: [4, 8, 6, 9, 9]

# 返回列表中最大的3个元素
largest = heapq.nlargest(3, nums)
print(largest)  # 输出: [9, 9, 8]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
'
运行
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/1020100
推荐阅读
相关标签
  

闽ICP备14008679号