Python 检查heapq是否包含值

Python 检查heapq是否包含值,python,queue,priority-queue,Python,Queue,Priority Queue,我使用heapq对象来存储我实现的类的对象 import heapq heap = [] element1 = Element('A', 1) element2 = Element('B', 2) element3 = Element('C', 3) heapq.heappush(heap, element1) heapq.heappush(heap, element2) heapq.heappush(heap, element3) 在我的class元素中,我覆盖了方法\uuucmp\uuu

我使用heapq对象来存储我实现的类的对象

import heapq

heap = []
element1 = Element('A', 1)
element2 = Element('B', 2)
element3 = Element('C', 3)
heapq.heappush(heap, element1)
heapq.heappush(heap, element2)
heapq.heappush(heap, element3)
在我的class元素中,我覆盖了方法
\uuucmp\uuuu
,以确保值是优先级

def __cmp__(self, other):
        return cmp(self.value, other.value)
现在我想写一个函数,检查堆是否包含元素,这样 如果我想检查
element=element('A',1)
是否在堆中,答案将是
True
,如果我想检查
element=element('A',100)
答案也将是
True
,但是如果我想检查
element=element('D',1)
答案将是
False

我如何实现这种方法?是否可以在不调用
pop()
方法的情况下检查
heapq
的元素?

Element
中添加方法
\uuuu eq\uuu
,这样您就可以在
中使用关键字
检查成员身份(不调用
\uu eq\uuu
代码
元素('A',1)==元素('A',1)
将给出
False
):

在python中,堆只是列表,因此只需使用以下命令,
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
将完成其余操作:

Element('A', 1) in heap
例子
工作原理是,实现
\uuuuuu eq\uuuu
来检查元素是否在堆中,以及
\uuuuuu cmp\uuuu
来对元素进行优先级排序。然而,它会产生一些奇怪的副作用。例如,
元素('A',1)
将同时是
=
到,
元素
只是值及其优先级的包装,仅用于此堆,或者,您是否必须出于其他原因使用该类?您能否添加更多关于该类的实际用途的信息,以及这是用于Python2还是Python3的信息?@tobias_k我必须将该类用于其他用途reasons@Ziva在这种情况下,,您可以特别注意,以不一致的方式实现
eq
cmp
不会在其他地方造成问题。我认为
\uuuueq\uuuu
应该只比较
,以便
(A,1)
=
(A,100)
@tobias\k这是可能的,但他可能希望允许重复,这取决于语义。让我们看看OP是怎么说的,如果需要,我会修改代码。谢谢你的观察!我认为这很清楚:“如果我检查element=element('A',100),答案也将是正确的”哈哈,对不起;)非常感谢。
Element('A', 1) in heap
import heapq

heap = []
element1 = Element('A', 1)
element2 = Element('B', 2)
element3 = Element('C', 3)
heapq.heappush(heap, element1)
heapq.heappush(heap, element2)
heapq.heappush(heap, element3)

print Element('A', 1) in heap      # True
print Element('A', 100) in heap    # True
print Element('D', 1) in heap      # False
heap = []
heapq.heappush(heap, (1, 'A'))
heapq.heappush(heap, (3, 'C'))
heapq.heappush(heap, (2, 'B'))

print('A' in zip(*heap)[1])
print(any('D' == b for a, b in heap)
True
False