【python Tips】那些事半功倍的标准库(3-heapq)

本文详细介绍了Python标准库heapq模块的使用,包括heapify堆化、heappush插入、heappop删除堆顶元素、heapreplace替换堆顶及merge合并堆等功能,并通过示例演示了如何在优先级队列中实现多重排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 模块:heapq

1.1 模块方法汇总

__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge',
           'nlargest', 'nsmallest', 'heappushpop']

"""
heappush: Push item onto heap, maintaining the heap invariant.
heappop: Pop the smallest item off the heap, maintaining the heap invariant.
heapify: ransform list into a heap, in-place, in O(len(x)) time.
heapreplace: Pop and return the current smallest value, and add the new item.
merge: Merge multiple sorted inputs into a single sorted output.
nlargest: Find the n smallest elements in a dataset. Equivalent to:  sorted(iterable, key=key)[:n]
nsmallest: Find the n largest elements in a dataset. Equivalent to:  sorted(iterable, key=key, reverse=True)[:n].
heappushpop: Fast version of a heappush followed by a heappop.
"""

1.2 方法详解

refer: Python标准库模块之heapq
refer: 创建堆

1.2.1 创建堆 heapify

  • 概念:
    创建堆 指的是初始化一个堆实例。在创建 堆 的过程中,我们也可以同时进行 堆化 操作。堆化 就是将一组数据变成 堆 的过程。

  • 创建方法:

    • 使用一个空列表,然后使用heapq.heappush()函数把值加入堆中;
    • 或者使用heap.heapify(list)转换列表成为堆结构
      时间复杂度: O(N)
      空间复杂度: O(N)
  • 语法:heapify(list)

    import heapq
    seqs = [5, 2, 4, 7, 11, 3, 12, 65, 34]
    heap = []
    for v in seqs:
        heapq.heappush(heap, v)
    print(heap)     # [2, 5, 3, 7, 11, 4, 12, 65, 34]
    
    heapq.heapify(seqs)
    print(seqs)     # [2, 5, 3, 7, 11, 4, 12, 65, 34]
    
    print([heapq.heappop(seqs) for _ in range(len(seqs))])   # out:[2, 3, 4, 5, 7, 11, 12, 34, 65]
    
    import heapq
    # 创建一个空的最小堆
    minHeap = []
    heapq.heapify(minHeap)
    
    # 创建一个空的最大堆
    # 由于Python中并没有内置的函数可以直接创建最大堆,所以一般我们不会直接创建一个空的最大堆。
    
    # 创建带初始值的「堆」, 或者称为「堆化」操作,此时的「堆」为「最小堆」
    heapWithValues = [3,1,2]
    heapq.heapify(heapWithValues)
    
    # 创建最大堆技巧
    # Python中并没有内置的函数可以直接创建最大堆。
    # 但我们可以将[每个元素*-1],再将新元素集进行「堆化」操作。此时,堆顶元素是新的元素集的最小值,也可以转换成原始元素集的最大值。
    # 示例
    maxHeap = [1,2,3]
    maxHeap = [-x for x in maxHeap]
    heapq.heapify(maxHeap)
    # 此时的maxHeap的堆顶元素是-3
    # 将-3转换为原来的元素3,既可获得原来的maxHeap中最大的值是3
    
    

1.2.2 插入元素 heappush

  • 语法:heappush(heap, item)
    # 最小堆插入元素
    heapq.heappush(minHeap, 1)
    # 最大堆插入元素
    # 元素乘以-1的原因是我们将最小堆转换为最大堆。
    heapq.heappush(maxHeap, 1*-1)
    

1.2.3 获取元素

堆获取元素通常指获取堆顶元素

  • 语法:heap[0]

    # 最小堆获取堆顶元素,即最小值
    minHeap[0]
    # 最大堆获取堆顶元素,即最大值
    # 元素乘以 -1 的原因是:我们之前插入元素时,将元素乘以 -1,所以在获取元素时,我们需要乘以 -1还原元素。
    maxHeap[0]*-1
    

1.2.4 删除堆顶元素 heapq.heappop

  • 语法:heapq.heappop(heap)

    # 最小堆删除堆顶元素
    heapq.heappop(seqs)
    # 最大堆删除堆顶元素
    heapq.heappop(seqs)
    

1.2.5 替换堆顶元素 heapq.heaprepalce

  • 语法: heapq.heapify(heap, item)

    import heapq
    
    seqs = [5, 2, 4, 7, 11, 3, 12, 65, 34]
    heapq.heapify(seqs)
    print(seqs)     # [2, 5, 3, 7, 11, 4, 12, 65, 34]
    heapq.heapreplace(seqs, 200)    
    print(seqs)     # [3, 5, 4, 7, 11, 200, 12, 65, 34]
    

1.3 示例

priority_queue = [(11,2,12), (1, 3, 23), (1, 1, 1), (42, 0, 12), (1, 1, 43)]
heapq.heapify(priority_queue)

# priority_queue = []
# for item in a:
#     heapq.heappush(priority_queue, (item[0], item[1], item[2]))
# (item[0], item[1], item[2]) 多元素按照索引顺序多重排序
print(priority_queue)
print(heapq.heappop(priority_queue))
print(priority_queue)
print(heapq.heappop(priority_queue))
print(priority_queue)
print(heapq.heappop(priority_queue))
print(priority_queue)

# 输出
[(1, 1, 1), (1, 1, 43), (11, 2, 12), (42, 0, 12), (1, 3, 23)]
(1, 1, 1)
[(1, 1, 43), (1, 3, 23), (11, 2, 12), (42, 0, 12)]
(1, 1, 43)
[(1, 3, 23), (42, 0, 12), (11, 2, 12)]
(1, 3, 23)
[(11, 2, 12), (42, 0, 12)]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值