我正在使用heapq包来处理图形。
让我们假设一个列表“堆”,由2个元组a和b表示(距离,节点)
import heapq
heap = []
a = (321,4)
b = (258,3)
heapq.heappush(heap,a)
heapq.heappush(heap,b)
有没有办法检查节点4是否在堆列表中?如果是的话,我怎么能得到它的距离?
使用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]))
OUTPUT:
The Distance of the node 4 is [321]
要么:
print("The Distance of the node {} is {}".format(node, str([x[0] for x in heap if x[1] == node]).strip("[]")))
OUTPUT:
The Distance of the node 4 is 321