如何检查 heapq 中是否有值
how checking if there is a value in a heapq
我正在使用 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]))
输出:
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("[]")))
输出:
The Distance of the node 4 is 321
我正在使用 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]))
输出:
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("[]")))
输出:
The Distance of the node 4 is 321