在 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,另一種是透過從各自的包中匯入它們來使用佇列。我們必須使用強制轉換方法將佇列更改為列表。

更新於: 2023 年 8 月 24 日

258 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.