Python3 queue module

 Python内建模块系列文章目录

说明:这些是Python3中的内建模块,直接导入后即可使用
 Python sortedcontainers module:有序列表、有序字典和有序集合

queue module:队列、优先级队列


目录

 Python内建模块系列文章目录

概要

一、LifoQueue

二、Queue

参考文献


概要

queue.Queue()        queue.PriorityQueue()

Methods: put(item), get(), qsize(), empty()


一、LifoQueue

LifoQueue遵循LIFO(Last in forst out)原则,和栈很像

queue.LifoQueue([maxsize=0])

maxsize用于指定栈的大小。默认maxsize=0,代表栈的大小没有限制

from queue import LifoQueue
q = LifoQueue(maxsize=0)

 Methods:

  1. put(item)
  2. get()  # 同list.pop()
  3. empty()
  4. qsize()
  5. full()

q为空不能用pop()

q为full不能用put

q = queue.LifoQueue(maxsize=5)    #LifoQueue created with maximum size of 5
print("Queue size:", q.qsize())

for i in range(0, 10, 2):
    print("Full:", q.full())                     #To check queue is full or not
    q.put(i)                                     #put element into the queue
print("Queue size:", q.qsize())                  #chech the size of the queue
print("Full:", q.full())

while not q.empty():                             # check if queue is empty
    print("Removed item from queue:", end=' ')
    print(q.get())                               #reterievr element from the queue
    print("Empty:", q.empty())
print("Queue size:", q.qsize())

二、Queue

速度和LifoQueue相当

进入队列的速度比list.append(val)略慢,出队列的速度比del list[0]快的多

用它当队列比用list当队列要快

Methods:

  1. put(item)  # 进入队列
  2. get()        # 同list.pop()
  3. empty()   
  4. qsize()    # 返回队列的大小
  5. full()
q = queue.Queue([maxsize=0])

三、PriorityQueue

优先级队列:将put的元素按照优先级排序,每次get到优先级最*的元素

  1. put(item)  # 进入队列
  2. get()        # 同list.pop()
  3. empty()   
  4. qsize()    # 返回队列的大小
  5. full()
q = queue.PriorityQueue([maxsize=0])
q.put([1,2])
q.put([4,3])
q.put([2,4])
while not q.empty():
    print(q.get())

# OUTPUT:
# [1,2]
# [2,4]
# [4,3]


总结

使用Queue()作为队列比list() 进入队列略慢,但出队列快的多

如果仅仅是力扣做题用list()比LifoQuueue()快

PriorityQueue()

外部链接:

Python Queue Module LifoQueue | Python | cppsecrets.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值