栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python---优先队列PriorityQueue

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python---优先队列PriorityQueue

优先队列PriorityQueue 单个数值
from queue import PriorityQueue
pq = PriorityQueue(maxsize=10)		# 创建最大容量为10的优先队列
pq.put(2)
pq.put(1)
pq.put(3)
pq.put(1)
print(pq.get())
print(pq.get())
print(pq.get())
--> 1
--> 1
--> 2
多个数值

当保存项包含多个不同类型的值时,按第一个值排序

from queue import PriorityQueue
pq = PriorityQueue()
pq.put(("b", 1))
pq.put(("a", 2))
pq.put(("c", 3))

print(pq.get())
--> ('a', 2)
from queue import PriorityQueue
pq = PriorityQueue()
pq.put((2, "a"))
pq.put((1, "b"))
pq.put((3, "c"))
print(pq.get())
--> (1, 'b')
保存类对象

当保存某个类的对象作为队列中元素时,可在类中通过 lt 函数控制元素之间的对比

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __lt__(self, other):
        return self.age < other.age		# age小的优先出队列


from queue import PriorityQueue
pq = PriorityQueue()

pq.put(Dog("a", 2))
pq.put(Dog("b", 1))
pq.put(Dog("c", 3))
p1 = pq.get()
p2 = pq.get()
print(p1.name, p1.age)
print(p2.name, p2.age)

--> b 1
--> a 2
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/307399.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号