python 标准库heapq的使用

import heapq


#用heapq 支持自定义对象
#heapq可以用默认list类型来创建堆结构,
#用[]来创建堆结构不建议给初始值,如果非得给的话建议先调用heapq.heapify进行转化
import random
a = []

for i in range(10):
    
    heapq.heappush(a, random.randint(1, 10))
    
print(a)

#堆顶端总是放着堆中最小值
print(a[0])

# 让heapq 支持自定义对象


class Item:
    
    def __init__(self, id, name):
        
        self.id = id
        self.name = 'leo'
        
    #需要实现lt 特殊方法
    def __lt__(self, other):
        
        return self.id < self.other
    
    
item = []

for _ in range(10):
    
    num = random.randint(1, 10)
    heapq.heappush(Item(id=num))
    
print(item[0])
原文地址:https://www.cnblogs.com/alplf123/p/10299561.html