Python教程-Python queue 队列优先级

位置:首页>文章>详情   分类: 教程分享 > Python教程   阅读(3753)   2023-03-28 11:29:14
队列


1.什么是队列优先级

  • 队列优先级是一种抽象数据类型,类似于常规队列或堆栈数据结构,但每个元素另外都具有与之关联的“优先级”。
  • 在优先级队列中,优先级高的元素先于优先级低的元素提供。
  • 如果两个元素具有相同的优先级,则将根据它们在队列中的顺序为其提供服务。

2. Python中的队列优先级实现

以下python程序使用该heapq模块实现简单的优先级队列:
$title(PriorityQueue.py)
import heapq
 
class PriorityQueue:
    def __init__(self):
        self._queue = []
        self._index = 0
 
    def push(self, item, priority):
        heapq.heappush(self._queue, (-priority, self._index, item))
        self._index += 1
 
    def pop(self):
        return heapq.heappop(self._queue)[-1]

3. Python队列优先级示例

让我们看一个如何使用上面创建的优先级队列的例子。
$title(example.py)
class Item:
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Item({!r})'.format(self.name)
 
>>> q = PriorityQueue()
 
>>> q.push(Item('l'), 1)
>>> q.push(Item('e'), 5)
>>> q.push(Item('f'), 4)
>>> q.push(Item('t'), 2)
>>> q.push(Item('so'), 1)
 
>>> q.pop()
Item('e')      #5
 
>>> q.pop()
Item('f')      #4
 
>>> q.pop()
Item('t')      #2
 
>>> q.pop()
Item('l')     #1
 
>>> q.pop()
Item('so')    #1

地址:https://www.leftso.com/article/738.html

相关阅读

​1.什么是队列优先级队列优先级是一种抽象数据类型,类似于常规队列或堆栈数据结构,但每个元素另外都具有与之关联的“优先级”
前言本教程学习在Python中使用CSV文件
Python简介​Python是一种流行的编程语言,由Guido van Rossum创建,并于1991年发布
一.前言俗话说,工欲善其事必先利其器,本教程主要讲解如何在sublime编辑器中安装python软件包,以实现自动完成等功能,并在sublime编辑器本身中运行build
前言在Python(或任何其他编程语言)中,注释用于解释源代码
Python –数据类型数据类型定义变量的类型
了解python中的变量,声明局部变量和全局变量
Python httplib2 简介学习使用Python httplib2模块
​Python关键字是python编程语言的保留字,这些关键字不能用于其他目的
Python string.startswith()方法用于检查特定文本模式(例如URL方案等)的字符串以什么开头