heapq(python库学习)

模块heapq中一些重要的函数

函 数描 述
heappush(heap, x)将x压入堆heap中
heappop(heap)从堆heap中弹出最小的元素
heapify(heap)让列表具备堆特征,没有返回列表
heapreplace(heap, x)弹出最小的元素,并将x压入堆heap中
nlargest(n, iter)返回iter中n个最大的元素
nsmallest(n, iter)返回iter中n个最小的元素
import heapq

创建堆的两种方式

  • 使用一个空列表,然后使用 heapq.heappush() 函数把值加入堆中
  • 使用 heap.heapify(list) 转换列表成为堆结构
nums = [2, 3, 5, 1, 54, 23, 132]
heap1 = []
for num in nums:
    heapq.heappush(heap1, num)  # 加入堆
print(heap1)
print([heapq.heappop(heap1) for _ in range(len(nums))])  # 堆排序结果
[1, 2, 5, 3, 54, 23, 132]
[1, 2, 3, 5, 23, 54, 132]
nums = [2, 3, 5, 1, 54, 23, 132]
heapq.heapify(nums)
print(nums)
[1, 2, 5, 3, 54, 23, 132]

两组有序序列的合并:合并成有序序列并进行迭代

heapq.merge(a,b) 函数,注意返回的是一个迭代器

a = [1, 3, 7, 10]
b = [2, 5, 6, 11]
print(heapq.merge(a, b))  #看到返回的是一个生成器类型
print([i for i in heapq.merge(a, b)])
print(list(heapq.merge(a, b)))
<generator object merge at 0x000001EFA5B6CD00>
[1, 2, 3, 5, 6, 7, 10, 11]
[1, 2, 3, 5, 6, 7, 10, 11]

访问堆内容

heapq.heappop(堆名称) 函数弹出堆中最小值

nums = [34, 2, 45, 23, 12]
heapq.heapify(nums)

print(heapq.heappop(nums))    #第一个最小值
print(heapq.heappop(nums))    #第二个最小值
print("Remainers: ",nums)
2
12
Remainers:  [23, 34, 45]

heapq.heaprepalce(堆名称,插入值) 函数 删除堆中最小元素并加入一个元素

nums = [1, 2, 4, 5, 3]
heapq.heapify(nums)

heapq.heapreplace(nums, 23)    #删除最小元素1在最后面的元素加入23
print(nums)
[2, 3, 4, 5, 23]

获取堆最大或最小值(单值或范围)

heapq.nlargest(范围,堆名称)heapq.nsmallest(范围,堆名称) 获取堆中最大或最小的范围值

nums = [1, 3, 4, 5, 2]
print(heapq.nlargest(3, nums))
print(heapq.nsmallest(3, nums))
[5, 4, 3]
[1, 2, 3]

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

from pprint import pprint
portfolio = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
]
sharesleast = heapq.nsmallest(3, portfolio, key=lambda s: s['shares'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
pprint(sharesleast) #返回最小的几个分享次数
pprint(expensive)  #返回最多的几个价格

[{'name': 'HPQ', 'price': 31.75, 'shares': 35},
 {'name': 'YHOO', 'price': 16.35, 'shares': 45},
 {'name': 'AAPL', 'price': 543.22, 'shares': 50}]
[{'name': 'AAPL', 'price': 543.22, 'shares': 50},
 {'name': 'ACME', 'price': 115.65, 'shares': 75},
 {'name': 'IBM', 'price': 91.1, 'shares': 100}]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值