Python内建模块系列文章目录
说明:这些是Python3中的内建模块,直接导入后即可使用
Python sortedcontainers module:有序列表、有序字典和有序集合
目录
概要
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:
- put(item)
- get() # 同list.pop()
- empty()
- qsize()
- 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:
- put(item) # 进入队列
- get() # 同list.pop()
- empty()
- qsize() # 返回队列的大小
- full()
q = queue.Queue([maxsize=0])
三、PriorityQueue
优先级队列:将put的元素按照优先级排序,每次get到优先级最*的元素
- put(item) # 进入队列
- get() # 同list.pop()
- empty()
- qsize() # 返回队列的大小
- 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()
外部链接: