как проверить, есть ли значение в heapq - PullRequest
0 голосов
/ 13 марта 2019

Я работаю с пакетом heapq для работы с графиками.

Предположим, список "куча", поданный 2 кортежей a и b, представляющих (расстояние, узел)

import heapq

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

Есть ли способ проверить, находится ли узел 4 в списке кучи? и если да, как я могу получить его расстояние?

1 Ответ

0 голосов
/ 13 марта 2019

Использование 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]

OR :

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