2014-03-29 216 views
2

我正在尋找一種優先級隊列,它允許我給出兩個優先級。 我想,它只是檢查的第一個值,然後在第二個 下面是一些代碼具有兩個優先級的優先級隊列Python

import Queue 

class Job(object): 
    def __init__(self, fpriority, spriority, description, iata , hops, cost): 
     self.fpriority = fpriority 
     self.spriority = spriority 

q = Queue.PriorityQueue() 

q.put(Job(2, 5, 'Mid-level job')) 
q.put(Job(2, 20, 'Low-level job')) 
q.put(Job(1, 20, 'Important job')) 

現在我想的元素

Important job 
Mid_level job 
Low_level job 

下列順序如何創建這樣的訂購一個隊列?

回答

2
class Job(object): 
    def __init__(self, fpriority, spriority, description, iata , hops, cost): 
     self.fpriority = fpriority 
     self.spriority = spriority 

    def __cmp__(self, other): 
     '''Comparisons for Python 2.x - it's done differently in 3.x''' 
     if self.fpriority > other.fpriority: 
      return 1 
     elif self.fpriority < other.fpriority: 
      return -1 
     else: 
      if self.spriority > other.spriority: 
       return 1 
      elif self.spriority < other.spriority: 
       return -1 
      else: 
       return 0 
4

只需使用(fpriority, spriority)元組作爲優先級。這將做你想要的排序(先比較,然後再打破關係)。

+0

你能寫一個小例子我不確定你的意思是什麼 –

1

使用NPE的策略 - 一個元組的隊列優先級,元組是(fpriority, spriority)

import Queue 

class Job(object): 
    def __init__(self, fpriority, spriority, description='blah', iata='foo' , hops='ample', cost='free pitchers'): 
     self.fpriority = fpriority 
     self.spriority = spriority 
     self.description = description 
    @property 
    def priority(self): 
     return (self.fpriority, self.spriority) 
    def __str__(self): 
     return self.description 

q = Queue.PriorityQueue() 

second = Job(2, 5, 'Mid-level job') 
third = Job(2, 20, 'Low-level job') 
first = Job(1, 20, 'Important job') 

q.put((second.priority, second)) 
q.put((third.priority, third)) 
q.put((first.priority, first)) 

while q.unfinished_tasks: 
    task = q.get() 
    print task, task[1] 
    q.task_done() 
>>> 
((1, 20), <__main__.Job object at 0x02A8F270>) Important job 
((2, 5), <__main__.Job object at 0x02A8F230>) Mid-level job 
((2, 20), <__main__.Job object at 0x02A8F250>) Low-level job 
>>> 

這應該爲任意數量的元組的優先項目的工作。

>>> 
>>> t = [(1,2),(1,1),(2,2),(2,1),(1,3)] 
>>> sorted(t) 
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2)] 
>>> t = [(2,2,67),(1,2,3),(1,1,0),(2,2,1),(2,1,78),(1,3,78),(1,2,2),(1,2,1),(1,1,6),(2,1,32)] 
>>> sorted(t) 
[(1, 1, 0), (1, 1, 6), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 78), (2, 1, 32), (2, 1, 78), (2, 2, 1), (2, 2, 67)] 
>>>