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)

  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Python,如果你使用priority_queue存储的是对象,你可以通过自定义排序函数来实现对priority_queue的排序。你可以使用heapq模块的方法来实现堆操作,并使用自定义的排序函数来指定对象的优先级。 举个例子,假设你有一个存储Person对象的priority_queue,你可以定义一个比较函数来指定Person对象的排序规则。比较函数应该返回一个负数、零或正数,分别表示第一个对象小于、等于或大于第二个对象。 下面是一个示例代码,演示了如何在Python使用priority_queue对Person对象进行排序: ```python import heapq class Person: def __init__(self, name, age): self.name = name self.age = age def __lt__(self, other): # 自定义对象的排序规则,比较年龄大小 return self.age < other.age # 创建一个存储Person对象的priority_queue priority_queue = [] # 添加一些Person对象到priority_queue heapq.heappush(priority_queue, Person('Alice', 25)) heapq.heappush(priority_queue, Person('Bob', 30)) heapq.heappush(priority_queue, Person('Charlie', 20)) # 从priority_queue弹出对象,按照自定义排序规则输出 while priority_queue: person = heapq.heappop(priority_queue) print(person.name, person.age) ``` 输出结果会按照Person对象的age属性进行排序,从小到大输出。在这个例子,我们重载了Person类的`__lt__`方法来定义对象的排序规则,使得priority_queue按照年龄的大小进行排序。 希望这个例子能帮助你理解如何在Python使用priority_queue对对象进行排序。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [STL priority_queue自定义排序实现方法详解](https://blog.csdn.net/weixin_39930557/article/details/111521369)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [[python3] 堆 优先队列(priorityqueue) heapq模块](https://blog.csdn.net/qq_35630119/article/details/119520033)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Python(一)数据结构和算法的20个练习题问答](https://blog.csdn.net/weixin_39882948/article/details/110994081)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值