2010-07-22 90 views
0

我想在python中構建一個優先級隊列,其中隊列包含不同的字典及其優先級數字。因此,當調用「get function」時,具有最高優先級(最低編號)的字典將被拉出隊列,並且在調用「add function」時,新字典將被添加到隊列中並根據其進行排序優先號碼。創建一個python優先級隊列

請幫忙...

在此先感謝!

回答

6

在標準庫中使用heapq模塊。

不指定你怎麼想優先事項字典相關聯,但這裏有一個簡單的實現:

import heapq 

class MyPriQueue(object): 
    def __init__(self): 
     self.heap = [] 

    def add(self, d, pri): 
     heapq.heappush(self.heap, (pri, d)) 

    def get(self): 
     pri, d = heapq.heappop(self.heap) 
     return d 
+0

+1對於標準庫,當然是使用堆。 – 2010-07-22 17:29:03

+0

以及我希望它可以在這種格式: if __name__ =='__main__': speech = Speak() firstDict = {'command_type':'say_string','control_command':'stop','priority ':'3 } secondDict = {'command_type':'say_string','control_command':'resume','priority': } thirdDict = {'command_type':'say_wav','control_command':無, '優先':1 } #將語音字典全球隊列,並打印出來 使用#using循環隊列 speech.add_to_queue(firstDict) speech.add_to_queue(secondDict) speech.add_to_queue(thirdDict) speech.loop_queue() – 2010-07-22 17:35:46

+0

請問我是否可以獲取代碼格式,這樣看起來就像使用正確格式的更好方式。 謝謝! – 2010-07-22 17:36:43

0

您可以通過添加一個字典對象的類做到這一點,裏面搜索。

2

這就是我通常存在於我的一些圖案會談一個側面說明:

class PriorityQueue(object): 
def __init__(self, key=lambda x: x): 
    self.l = [] 
    self.key = key 
def __len__(self): 
    return len(self.l) 
def push(self, obj): 
    heapq.heappush(self.l, (self.key(obj), obj)) 
def pop(self): 
    return heapq.heappop(self.l)[-1] 

的OP的要求顯然是實例PriorityQueue時使用operator.itemgetter('priority')作爲key參數(在頂部需要一個import operator模塊,當然;-)。