heapq( Heap queue algorithm)庫

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
發佈了62 篇原創文章 · 獲贊 8 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章