Python【queue】
文章目录
- Python【queue】
- 1.Queue
- 2.LifoQueue
- 4.PriorityQueue
python中queue包括FIFO(先入先出)队列Queue、LIFO(后入先出)队列LifoQueue、优先级队列PriorityQueue
1.Queue
from queue import Queue
q = Queue(maxsize=10)
# Queue.put()写入队列
q.put(2)
# Queue.qsize()返回队列的大小
print(q.qsize())
# Queue.empty()判断队列是否为空
print(q.empty())
# Queue.full()判断队列是否为满
print(q.full())
# Queue.get()出队
print(q.get())
输出:
1
False
False
2
2.LifoQueue
可以当作栈来使用
from queue import LifoQueue
lq = LifoQueue()
lq.put(2)
lq.put(3)
print(lq.qsize())
print(lq.get())
print(lq.qsize())
输出:
2
3
1
4.PriorityQueue
常用put(入队列)与get(出队列),queue(查看队列中的元素)。
put方法要注意方入队列的是一个元组,不要忘记括号,默认情况下队列根据元组的第一个元素进行排序。越小的优先级越低。
get方法是将优先级最低的一个元素出队列
from queue import PriorityQueue
pq = PriorityQueue()
pq.put((1,'hello'))
pq.put((10,'world'))
pq.put((5,'python'))
while not pq.empty():
print(pq.get())
输出:
(1, 'hello')
(5, 'python')
(10, 'world')