python的堆heap操作


python沒有實現專門的堆數據結構,但是提供了一系列方法,可以操作在list上,實現堆的功能

import heapq
# 將x壓入堆中
heapq.heappush(heap, x)   
# 從堆中彈出最小的元素                                     
heapq.heappop(heap)    
# 讓列表具備堆特征                                  
heapq.heapify(heap) 
# 彈出最小的元素,並將x壓入堆中                                      
heapq.heapreplace(heap, x)  
# 返回iter中n個最大的元素                          
heapq.nlargest(n, iter) 
# 返回iter中n個最小的元素                                      
heapq.nsmallest(n, iter)                                   

# 從一個list中獲取最大的元素
max_column_data = heapq.nlargest(1, temp_list, key=lambda item: len(item))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM