OKちょうどこの質問を閉鎖します。私が何をしたのか:
ADTを匹敵させる:__lt__()
を実装してください。
def __lt__(self, other):
selfPriority = (self.priority, self.pid)
otherPriority = (other.priority, other.pid)
return selfPriority < otherPriority
この方法で、私は単にqueue.put(obj)
を使用することができ、私は優先順位とカウンタは、常に比較され、どの2つのカウンターが今まで持っていない場合@larsmansは
「を言うに右であることがわかりました同じ値であれば、トリプル全体が同等です "
[email protected]:~$ python3.2
Python 3.2.2 (default, Sep 5 2011, 21:17:14)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Test:
... def __init__(self, name):
... self.name = name
...
>>> from queue import PriorityQueue
>>> q = PriorityQueue()
# duplicate priorities triggering unorderable error
>>> q.put((2, Test("test1")))
>>> q.put((1, Test("test1")))
>>> q.put((3, Test("test1")))
>>> q.put((3, Test("test1")))
>>> q.put((3, Test("test2")))
>>> while not q.empty():
... print(q.get().name)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/lib/python3.2/queue.py", line 195, in get
item = self._get()
File "/usr/lib/python3.2/queue.py", line 245, in _get
return heappop(self.queue)
TypeError: unorderable types: Test() < Test()
# unique priority fields thus avoiding the problem
>>> q = PriorityQueue()
>>> q.put((3, Test("test1")))
>>> q.put((5, Test("test5")))
>>> while not q.empty():
... print(q.get()[1].name)
...
test1
test5
オブジェクトを優先度と比較できない場合は、 '(priority、obj)'のペアをPQに挿入します。 –
@larsmans、コードからhttp://stackoverflow.com/a/9289760/292291、 'PriorityQueue.put(self、(priority、self.counter、item))'すでに同様のことをしました –
@JiewMeng:if優先度とカウンタは常に比較可能であり、2つのカウンタの値が同じではない場合、トリプル全体が同等です。 –