Python';什么是heapq库?
我的印象是,第一个值决定了值在堆中的位置,但事实似乎并非如此Python';什么是heapq库?,python,python-2.7,heap,Python,Python 2.7,Heap,我的印象是,第一个值决定了值在堆中的位置,但事实似乎并非如此 from __future__ import print_function import heapq q = [] heapq.heappush(q, (10, 11)) heapq.heappush(q, (11, 12)) heapq.heappush(q, (9, 10)) print(q) 这给了我一个 [(9, 10), (11, 12), (10, 11)] 然而,我期待的是这样的输出 [(9, 10), (10,
from __future__ import print_function
import heapq
q = []
heapq.heappush(q, (10, 11))
heapq.heappush(q, (11, 12))
heapq.heappush(q, (9, 10))
print(q)
这给了我一个
[(9, 10), (11, 12), (10, 11)]
然而,我期待的是这样的输出
[(9, 10), (10, 11), (11, 12)]
heapq
上的条件不是所提供列表上的“排序保证”。相反,它保证q[k]
sorted_q = [heappop(q) for i in range(len(q))
>>> print sorted_q
[(9, 10), (10, 11), (11, 12)]
0
1 2
2 5 3 4
0
2 1
5 3 4 2
[0, 1, 2, 2, 5, 3, 4]
[0, 2, 1, 5, 3, 4, 2]