如何让 heapq 评估特定属性的堆? [英] How to make heapq evaluate the heap off of a specific attribute?

查看:11
本文介绍了如何让 heapq 评估特定属性的堆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望保存一堆对象,而不仅仅是数字.它们将具有堆可以排序的整数属性.在python中使用堆的最简单方法是heapq,但是在使用heapq时如何告诉它按特定属性排序?

I wish to hold a heap of objects, not just numbers. They will have an integer attribute in them that the heap can sort by. The easiest way to use heaps in python is heapq, but how do I tell it to sort by a specific attribute when using heapq?

推荐答案

heapq 以与 list.sort 相同的方式对对象进行排序,因此只需定义一个方法 __cmp__() 在您的类定义中,它将自身与同一类的另一个实例进行比较:

heapq sorts objects the same way list.sort does, so just define a method __cmp__() within your class definition, which will compare itself to another instance of the same class:

def __cmp__(self, other):
    return cmp(self.intAttribute, other.intAttribute)

适用于 Python 2.x.

Works in Python 2.x.

在 3.x 中使用:

def __lt__(self, other):
    return self.intAttribute < other.intAttribute

这篇关于如何让 heapq 评估特定属性的堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆