2017-07-17 44 views
6
阵列

python heap implementation的使用一个简单的例子是定义堆键元组

>>> from heapq import heappush, heappop 
>>> heap = [] 
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] 
>>> for item in data: 
     heappush(heap, item) 

在更复杂的情形中,我有元组的像

tuples = [(5,"foo",True),(2,"bar", False),(8,"foobar",True)] 

阵列,并希望使用每个元组的第一个条目作为堆键,即元组应该根据堆中的数字排序。

我该怎么做?

回答

4

您可以直接使用元组。如Python documentation explicitly makes note的用法如下:

堆元素可以是元组。

>>> h = [] 
>>> heappush(h, (5, 'write code')) 
>>> heappush(h, (7, 'release product')) 
>>> heappush(h, (1, 'write spec')) 
>>> heappush(h, (3, 'create tests')) 
>>> heappop(h) 
(1, 'write spec') 

元组简单地推到堆,并在需要时弹出他们关闭:这个被跟踪是沿着主记录分配比较值(如任务优先级)有用

>>> from heapq import heappush, heappop 
>>> 
>>> heap = [] 
>>> tuples = [(5,"foo",True),(2,"bar", False),(8,"foobar",True)] 
>>> 
>>> for tup in tuples: 
...  heappush(heap, tup) 
... 
>>> heappop(heap) 
(2, 'bar', False) 

因为the implementation for heap使用默认的排序元组

while pos > startpos: 
    ... 
    if newitem < parent: 
     ... 
    ... 
... 

和Python元组排序逐个元件,连接确定你想要排序的元组首先到达的对象。