python如何在自定义类上使用堆排序

2025-12-01 0 38,612

1、说明

我们留给自定义类的唯一解决方案是实际重写比较运算符。遗憾的是,这使我们局限于对每个类只能进行一种比较。在我们的示例中,我们被局限于按年份对Movie对象进行排序。

但是,它确实让我们演示了在自定义类上使用堆排序。我们来定义Movie类:

2、实例

from heapq import heappop, heappush
 
class Movie:
    def __init__(self, title, year):
        self.title = title
        self.year = year
 
    def __str__(self):
        return str.format("Title: {}, Year: {}", self.title, self.year)
 
    def __lt__(self, other):
        return self.year < other.year
 
    def __gt__(self, other):
        return other.__lt__(self)
 
    def __eq__(self, other):
        return self.year == other.year
 
    def __ne__(self, other):
        return not self.__eq__(other)

以上就是python在自定义类上使用堆排序的方法,希望能对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 python如何在自定义类上使用堆排序 https://www.zhiup.top/2156.html

相关