python如何在自定义类上使用堆排序
发布时间:2024-08-27 13:43:37

1、说明
我们留给自定义类的唯一解决方案是实际重写比较操作符。不幸的是,这使得我们局限于比较每个类别。在我们的例子中,我们仅限于按年份对Movie对象进行排序。
然而,它确实让我们演示了在自定义类中使用堆排序。让我们定义Movie类:
2、实例
fromheapqimportheappop,heappush
classMovie:
def__init__(self,title,year):
self.title=title
self.year=year
def__str__(self):
returnstr.format("Title:{},Year:{}",self.title,self.year)
def__lt__(self,other):
returnself.year<other.year
def__gt__(self,other):
returnother.__lt__(self)
def__eq__(self,other):
returnself.year==other.year
def__ne__(self,other):
returnnotself.__eq__(other)以上是python在自定义类中使用堆排序的方法,希望对大家有所帮助。更多Python学习指南:python基础教程
本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。
