heapq( Heap queue algorithm)库
从集合中取前n个最大,或最小的值
nlargest(n,iterable)前n个最大的,nsmallest(n,iterable)前n个最小的
import heapq
nums=[1,23,32,45,67,21,78,12]
print("3 largest",heapq.nlargest(3,nums))
print("3 smallest",heapq.nsmallest(3,nums))
3 largest [78, 67, 45]
3 smallest [1, 12, 21]
从字典中取前n个最大,或最小的值
nlargest(n,dicts,key)按照key取前n个最大的,nsmallest(n,dicts,key)按照key取前n个最小的
dicts=[
{'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}
]
print("2 largest",heapq.nlargest(2,dicts,key=lambda s:s['price']))
print("2 smallest",heapq.nsmallest(2,dicts,key=lambda s:s['price']))
2 largest [{'name': 'AAPL', 'price': 543.22, 'shares': 50}, {'name': 'ACME', 'price': 115.65, 'shares': 75}]
2 smallest [{'name': 'YHOO', 'price': 16.35, 'shares': 45}, {'name': 'FB', 'price': 21.09, 'shares': 200}]
heapify(X),将list X转换为堆
print("heap before:",nums)
heapq.heapify(nums)
print("heap after:",nums)
heap before: [1, 23, 32, 45, 67, 21, 78, 12]
heap after: [1, 12, 21, 23, 67, 32, 78, 45]
heappush(heap, item)
往堆里push一个元素
heapq.heappush(nums,10)
print("push 10 :",nums)
push 10 : [1, 10, 21, 12, 67, 32, 78, 45, 23]
heappop(heap)
从堆中pop一个最小的值,并从堆中移除这个值, 如果heap为空,抛出异常:IndexError: index out of range
smallest = heapq.heappop(nums)
print(smallest)
print("pop after:",nums)
#smallest = heapq.heappop([])
1
pop after: [10, 12, 21, 23, 67, 32, 78, 45]
heappushpop(heap, item)
push一个元素 , 然后pop一个最小的元素,类似与先调用一个 heappush() 然后再调用一个heappop方法
smallest = heapq.heappushpop(nums,100)
print("heappushpop 100, ",smallest)
###push一个最小的值,
smallest = heapq.heappushpop(nums,1)
print("heappushpop smallest value 1 and then return :",smallest)
heappushpop 100, 10
heappushpop smallest value 1 and then return : 1
heapreplace(heap, item)
先pop最小的值,然后再push item,如果heap为空,抛出异常:IndexError: index out of range
smallest = heapq.heapreplace(nums,1)
print("heapreplace smallest value 1 and then return :",smallest)
heapreplace smallest value 1 and then return : 12
merge(*iterables, key=None, reverse=False)
合并多个集合,返回堆排序后的数据,类型为 iterator
newheap = heapq.merge(nums,[10,11,23])
print(newheap)
for item in newheap:
print(item)
<generator object merge at 0x0000000004EB4AF0>
1
10
11
23
21
23
45
67
32
78
100