如何检查heapq中是否有值

时间:2019-03-13 10:53:47

标签: python graph heap-memory heapsort

我正在使用heapq软件包以便使用图形。

让我们假设一个列表“ heap”,由表示(distance,node)的两个元组a和b填充

import heapq

heap = []
a = (321,4)
b = (258,3)
heapq.heappush(heap,a)
heapq.heappush(heap,b)

是否可以检查节点4是否在堆列表中?如果是,我如何获得距离?

1 个答案:

答案 0 :(得分:0)

使用any

import heapq

heap = []
a = (321,4)
b = (258,3)
heapq.heappush(heap,a)
heapq.heappush(heap,b)
node = 4
if any(node in d for d in heap):
     print("The Distance of the node {} is {}".format(node, [x[0] for x in heap if x[1] == node]))

输出

The Distance of the node 4 is [321]

OR

print("The Distance of the node {} is {}".format(node, str([x[0] for x in heap if x[1] == node]).strip("[]")))

输出

The Distance of the node 4 is 321