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

358次阅读
没有评论

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

自定义类上使用堆排序说明

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

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

自定义类上使用堆排序实例

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在自定义类上使用堆排序的方法,希望能对大家有所帮助。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-03发表,共计666字。
新手QQ群:570568346,欢迎进群讨论 Python51学习