python中PriorityQueue的理解

PriorityQueue是优先级队列。越小的优先级越高,会被先取出。

下面的代码运行正常。

# 示例1
tsq = queue.PriorityQueue()    
tsq.put_nowait((0, '123', ['abc', 'efg'], 0))
tsq.put_nowait((0, '456', ['abc'], 0))

下面的代码运行报错。

# 示例2
tsq = queue.PriorityQueue()
tsq.put_nowait((0, '123', {"name":'abc', "age":'efg'}, 0))
tsq.put_nowait((0, '123', {"name":'abc'}, 0))

原因:
PriorityQueue是优先级队列,优先级排序使用了堆排序,这一操作会对压入的元素进行比较。示例2中压入的元素是tuple,两个tuple相比较是将tuple中元素逐个比较。示例2中压入的两个tuple的前两个元素都相同,第三个元素{"name":'abc', "age":'efg'}{"name":'abc'}都是字典,字典是不能比较大小的。
所以会报TypeError: '<' not supported between instances of 'dict' and 'dict'的错误。

PriorityQueue的正确使用方式,应该是如下两种,使用tuple的第一个元素作为优先级数字,或者自定义类中重定义__lt__方法,使得类实例能够相互比较。

# 示例3
tsq = queue.PriorityQueue()
tsq.put_nowait((0,{'task_name': 'aaa'}))  # tuple包含两个元素,第一个是优先级,第二个是数据
tsq.put_nowait((1, {'task_name', 'bbbb'})) 
# 示例4
import queue


class Task(object):
    def __init__(self, priority, name):
        self.priority = priority
        self.name = name

    def __str__(self):
        return "Task(priority={p}, name={n})".format(p=self.priority, n=self.name)

    def __lt__(self, other):
    	""" 定义<比较操作符。 """
        return self.priority < other.priority


tsq = queue.PriorityQueue()
tsq.put_nowait(Task(3, "task1"))  # 自定义的类定义了__lt__, 可以比较大小
tsq.put_nowait(Task(1, "task2"))
print(tsq.get())  # return: Task(priory=1, name=task2)

你可能感兴趣的:(Python,python)