📜  Python中的队列

📅  最后修改于: 2022-05-13 01:55:15.321000             🧑  作者: Mango

Python中的队列

与堆栈一样,队列是一种线性数据结构,以先进先出 (FIFO) 的方式存储项目。对于队列,最近最少添加的项目首先被删除。队列的一个很好的例子是资源的任何消费者队列,其中首先服务的消费者。

Python中的队列

与队列相关的操作是:

  • 入队将项目添加到队列中。如果队列已满,则称其为溢出条件 - 时间复杂度:O(1)
  • 出队从队列中删除一个项目。项目的弹出顺序与它们被推送的顺序相同。如果队列为空,则称其为下溢条件 - 时间复杂度:O(1)
  • Front:从队列中获取最前面的项目 - 时间复杂度:O(1)
  • 后:从队列中获取最后一项 - 时间复杂度:O(1)

执行

在Python中有多种实现队列的方法。本文介绍了使用Python库中的数据结构和模块实现队列。
Python中的队列可以通过以下方式实现:

  • 列表
  • 集合.deque
  • 队列.队列

使用列表实现

List 是 Python 的内置数据结构,可以用作队列。使用 append() 和 pop()函数代替 enqueue() 和 dequeue()。但是,为此目的,列表非常慢,因为在开头插入或删除一个元素需要将所有其他元素移动一个,需要 O(n) 时间。

Python3
# Python program to
# demonstrate queue implementation
# using list
 
# Initializing a queue
queue = []
 
# Adding elements to the queue
queue.append('a')
queue.append('b')
queue.append('c')
 
print("Initial queue")
print(queue)
 
# Removing elements from the queue
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
 
print("\nQueue after removing elements")
print(queue)
 
# Uncommenting print(queue.pop(0))
# will raise and IndexError
# as the queue is now empty


Python3
# Python program to
# demonstrate queue implementation
# using collections.dequeue
 
 
from collections import deque
 
# Initializing a queue
q = deque()
 
# Adding elements to a queue
q.append('a')
q.append('b')
q.append('c')
 
print("Initial queue")
print(q)
 
# Removing elements from a queue
print("\nElements dequeued from the queue")
print(q.popleft())
print(q.popleft())
print(q.popleft())
 
print("\nQueue after removing elements")
print(q)
 
# Uncommenting q.popleft()
# will raise an IndexError
# as queue is now empty


Python3
# Python program to
# demonstrate implementation of
# queue using queue module
 
 
from queue import Queue
 
# Initializing a queue
q = Queue(maxsize = 3)
 
# qsize() give the maxsize
# of the Queue
print(q.qsize())
 
# Adding of element to queue
q.put('a')
q.put('b')
q.put('c')
 
# Return Boolean for Full
# Queue
print("\nFull: ", q.full())
 
# Removing element from queue
print("\nElements dequeued from the queue")
print(q.get())
print(q.get())
print(q.get())
 
# Return Boolean for Empty
# Queue
print("\nEmpty: ", q.empty())
 
q.put(1)
print("\nEmpty: ", q.empty())
print("Full: ", q.full())
 
# This would result into Infinite
# Loop as the Queue is empty.
# print(q.get())


输出:

Initial queue
['a', 'b', 'c']

Elements dequeued from queue
a
b
c

Queue after removing elements
[]




Traceback (most recent call last):
  File "/home/ef51acf025182ccd69d906e58f17b6de.py", line 25, in 
    print(queue.pop(0))
IndexError: pop from empty list



使用 collections.deque 实现

Python中的队列可以使用集合模块中的 deque 类来实现。在我们需要从容器两端进行更快的追加和弹出操作的情况下,双端队列优于列表,因为与提供 O(n) 时间复杂度的列表相比,双端队列为追加和弹出操作提供 O(1) 时间复杂度.使用 append() 和 popleft() 函数代替 enqueue 和 deque。

Python3

# Python program to
# demonstrate queue implementation
# using collections.dequeue
 
 
from collections import deque
 
# Initializing a queue
q = deque()
 
# Adding elements to a queue
q.append('a')
q.append('b')
q.append('c')
 
print("Initial queue")
print(q)
 
# Removing elements from a queue
print("\nElements dequeued from the queue")
print(q.popleft())
print(q.popleft())
print(q.popleft())
 
print("\nQueue after removing elements")
print(q)
 
# Uncommenting q.popleft()
# will raise an IndexError
# as queue is now empty

输出:

Initial queue
deque(['a', 'b', 'c'])

Elements dequeued from the queue
a
b
c

Queue after removing elements
deque([])



Traceback (most recent call last):
  File "/home/b2fa8ce438c2a9f82d6c3e5da587490f.py", line 23, in 
    q.popleft()
IndexError: pop from an empty deque



使用 queue.Queue 实现

Queue 是Python的内置模块,用于实现队列。 queue.Queue(maxsize) 将变量初始化为最大大小为 maxsize。 maxsize 为零“0”表示无限队列。该队列遵循先进先出规则。
此模块中有各种可用的功能:

  • maxsize – 队列中允许的项目数。
  • empty() – 如果队列为空,则返回 True,否则返回 False。
  • full() – 如果队列中有 maxsize 个项目,则返回 True。如果队列是用 maxsize=0(默认值)初始化的,那么 full() 永远不会返回 True。
  • get() – 从队列中移除并返回一个项目。如果队列为空,请等到有可用的项目。
  • get_nowait() – 如果一个项目立即可用,则返回一个项目,否则引发 QueueEmpty。
  • put(item) – 将一个项目放入队列。如果队列已满,请等到有空闲插槽可用后再添加项目。
  • put_nowait(item) – 将一个项目放入队列而不阻塞。如果没有立即可用的空闲槽,则提高 QueueFull。
  • qsize() – 返回队列中的项目数。

Python3

# Python program to
# demonstrate implementation of
# queue using queue module
 
 
from queue import Queue
 
# Initializing a queue
q = Queue(maxsize = 3)
 
# qsize() give the maxsize
# of the Queue
print(q.qsize())
 
# Adding of element to queue
q.put('a')
q.put('b')
q.put('c')
 
# Return Boolean for Full
# Queue
print("\nFull: ", q.full())
 
# Removing element from queue
print("\nElements dequeued from the queue")
print(q.get())
print(q.get())
print(q.get())
 
# Return Boolean for Empty
# Queue
print("\nEmpty: ", q.empty())
 
q.put(1)
print("\nEmpty: ", q.empty())
print("Full: ", q.full())
 
# This would result into Infinite
# Loop as the Queue is empty.
# print(q.get())

输出:

0

Full:  True

Elements dequeued from the queue
a
b
c

Empty:  True

Empty:  False
Full:  False