函 数 | 描 述 |
---|---|
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
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)))
[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}]