Python标准库模块之heapq

功能:该模块提供了堆排序算法的实现,比如排序算法,就可以用这个实现啦

1. 创建堆

heapq有两种方式创建堆

一种是使用一个空列表,然后使用heapq.heappush()函数把值加入堆中,

另外一种就是使用heap.heapify(list)转换列表成为堆结构

import heapq
# 第一种
"""函数定义:
heapq.heappush(heap, item)
    - Push the value item onto the heap, maintaining the heap invariant.
heapq.heappop(heap)
    - Pop and return the smallest item from the heap, maintaining the heap invariant.
    If the heap is empty, IndexError is raised. To access the smallest item without popping it, use heap[0].
"""
nums = [2, 3, 5, 1, 54, 23, 132]
heap = []
for num in nums: 
    heapq.heappush(heap, num)  # 加入堆

print(heap[0])  # 如果只是想获取最小值而不是弹出,使用heap[0]
print([heapq.heappop(heap) for _ in range(len(nums))])  # 堆排序结果

# out: [1, 2, 3, 5, 23, 54, 132]

# 第二种
nums = [2, 3, 5, 1, 54, 23, 132]
heapq.heapify(nums)
print([heapq.heappop(heap) for _ in range(len(nums))])  # 堆排序结果
# out: [1, 2, 3, 5, 23, 54, 132]

2. 访问堆内容

堆创建好后,可以通过`heapq.heappop() 函数弹出堆中最小值

import heapq
nums = [2, 43, 45, 23, 12]
heapq.heapify(nums)
print(heapq.heappop(nums))
# out: 2

# 如果需要所有堆排序后的元素
result = [heapq.heappop(nums) for _ in range(len(nums))]
print(result)
# out: [12, 23, 43, 45]

如果需要删除堆中最小元素并加入一个元素,可以使用heapq.heaprepalce() 函数

import heapq
nums = [1, 2, 4, 5, 3]
heapq.heapify(nums)
heapq.heapreplace(nums, 23)
print([heapq.heappop(nums) for _ in range(len(nums))])

# out: [2, 3, 4, 5, 23]

3.获取堆最大或最小值

如果需要获取堆中最大或最小的范围值,则可以使用heapq.nlargest()或heapq.nsmallest()函数

这两个函数还接受一个key参数,用于dict或其他数据结构类型使用

堆的值可以是元组类型,可以实现对带权值的元素进行排序。

anyway,heapq其实就是对排序功能,因为已经排序了,所以heappop() 就是弹出下标为0,也就是第一个值,其次就是使用nlargest或者nsmallest()找出其中的最大最小值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值