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)
由于双端队列是栈、队列和向量的超集,我们可以将其用作任何一个。在这里,我们首先创建一个双端队列,然后将其强制转换为列表以使用它。
示例
# 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:使用队列
在这种方法中,我们将使用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_name是队列的名称)。在这里,时间和空间的复杂度都是O(N)。
结论
在本教程中,我们实现了将Python中的队列转换为列表的程序。为了将队列转换为列表,我们看到了两种方法,一种是使用deque,另一种是使用从相应包中导入的队列。我们必须使用强制转换的方法将队列转换为列表。