在 Python 中将队列转储到列表或数组中
队列是一种线性数据结构,它遵循 FIFO 原则,即每个元素都从后端添加到队列中,元素从前端提取,并使用先进先出的原则。在列表中,我们可以访问每个元素,而在队列中,我们只能访问第一个元素。在本教程中,我们将学习两种将队列转换为列表的方法。
在 Python 中创建队列
队列是一种线性数据结构,它遵循先进先出的属性,要在 Python 中使用队列,我们必须从 Python 的 collections 包中导入 deque。
示例
# import deque from collections
from collections import deque
# initialize a deque element
queue = deque()
# adding elements to the queue
queue.append(1)
queue.append(2)
queue.append(3)
queue.append(4)
# current queue is
print(queue)
# popping elements from queue
queue.popleft()
# printing next element
print('Current first element of the queue is:', queue.popleft())
输出
deque([1, 2, 3, 4]) Current first element of the queue is: 2
在队列中,将元素添加到后端和删除第一个元素的时间复杂度为 O(1)。
方法 1:使用 Deque
由于 deque 是栈、队列和向量的超集,因此我们可以将其用作其中任何一个。在这里,我们将首先创建一个 deque,然后通过将其转换为列表来将其用作列表。
示例
# import deque from collections
from collections import deque
# initialize a deque element
queue = deque()
# adding elements to the queue
queue.append(1)
queue.append(2)
queue.append(3)
queue.append(4)
# current queue is
print('Current queue is:', queue)
# printing the type of the current data structure
print(type(queue))
#casting current queue to the list
print('Converting current queue to list')
lis = list(queue)
print('Current list is: ', lis)
# printing the type of the current data structure
print(type(lis))
输出
Current queue is: deque([1, 2, 3, 4]) <class 'collections.deque'> Converting current queue to list Current list is: [1, 2, 3, 4] <class 'list'>
在上面的代码中,我们首先通过从 collections 中导入 deque 创建了一个队列,然后将其转换为队列并打印所有所需的参数。
上面代码的时间和空间复杂度是线性的,即 O(N),其中 N 是队列中元素的总数。
方法 2:使用 Queue
在这种方法中,我们将使用 Python 的 Queue 类中的队列数据结构,然后通过与前面代码类似的转换将其转换为列表。
示例
# import Queue from queue
from queue import Queue
# initialize a deque element
q = Queue()
# adding elements to the queue
q.put(1)
q.put(2)
q.put(3)
q.put(4)
q.put(5)
# current queue is
print('Current queue is:', q.queue)
# printing the type of the current data structure
print(type(q))
#casting current queue to the list
print('Converting current queue to list')
lis = list(q.queue)
print('Current list is: ', lis)
# printing the type of the current data structure
print(type(lis))
输出
Current queue is: deque([1, 2, 3, 4, 5]) <class 'queue.Queue'> Converting current queue to list Current list is: [1, 2, 3, 4, 5] <class 'list'>
队列数据结构不能直接迭代,为此,我们必须使用 queue_name.queue(其中 queue_name 是队列的名称)使其可迭代以进行打印以及转换为列表。在这里,时间和空间复杂度再次为 O(N)。
结论
在本教程中,我们实现了一个程序,用于将 Python 中的队列转换为列表。为了将队列转换为列表,我们看到了两种方法,第一种是使用 deque,另一种是通过从各自的包中导入它们来使用队列。我们必须使用强制转换方法将队列更改为列表。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP