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

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

问题描述

我想持有一堆物体,而不仅仅是数字。他们将在它们中有一个整数属性,堆可以排序。在python中使用堆的最简单的方法是heapq,但是当使用heapq时,如何使用特定的属性对它进行排序?

解决方案

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

  def __cmp __(self,other):
return cmp(self.intAttribute,other.intAttribute)

在Python 2.x中使用



在3.x中使用:

 code> def __lt __(self,other):
return self.intAttribute< other.intAttribute


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 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)

Works in Python 2.x.

In 3.x use:

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

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

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