先决条件: Python的队列
这里给出了一个队列,我们的任务是将队列转储到列表或数组中。我们将看到两种方法来实现我们的解决方案的目标。
示例 1:
在这个例子中,我们将使用集合包创建一个队列,然后将其转换为列表
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')
# display the queue
print("Initial queue")
print(q,"\n")
# display the type
print(type(q))
Python3
# convert into list
li = list(q)
# display
print("Convert into the list")
print(li)
print(type(li))
Python3
from queue import Queue
# Initializing a queue
que = Queue()
# Adding elements to a queue
que.put(1)
que.put(2)
que.put(3)
que.put(4)
que.put(5)
# display the queue
print("Initial queue")
print(que.queue)
# casting into the list
li = list(que.queue)
print("\nConverted into the list")
print(li)
输出:
Initial queue
deque(['a', 'b', 'c'])
让我们创建一个列表并将其转换为:
蟒蛇3
# convert into list
li = list(q)
# display
print("Convert into the list")
print(li)
print(type(li))
输出:
Convert into the list
['a', 'b', 'c']
示例 2:
在本例中,我们将使用 queue 模块创建一个队列,然后将其转换为列表。
蟒蛇3
from queue import Queue
# Initializing a queue
que = Queue()
# Adding elements to a queue
que.put(1)
que.put(2)
que.put(3)
que.put(4)
que.put(5)
# display the queue
print("Initial queue")
print(que.queue)
# casting into the list
li = list(que.queue)
print("\nConverted into the list")
print(li)
输出:
Initial queue
deque([1, 2, 3, 4, 5])
Converted into the list
[1, 2, 3, 4, 5]