Python雙端佇列


雙端佇列(或兩端佇列)具有從任一端新增和刪除元素的功能。 Deque模組是集合庫的一部分。 它具有新增和刪除可以直接用引數呼叫的元素的方法。 在下面的程式中,將匯入collections模組並宣告一個雙端佇列。 不需要任何類,直接使用內建的實現這些方法。

引數以下程式碼實現 -

import collections
# Create a deque
DoubleEnded = collections.deque(["Mon","Tue","Wed"])
print (DoubleEnded)

# Append to the right
print("Adding to the right: ")
DoubleEnded.append("Thu")
print (DoubleEnded)

# append to the left
print("Adding to the left: ")
DoubleEnded.appendleft("Sun")
print (DoubleEnded)

# Remove from the right
print("Removing from the right: ")
DoubleEnded.pop()
print (DoubleEnded)

# Remove from the left
print("Removing from the left: ")
DoubleEnded.popleft()
print (DoubleEnded)

# Reverse the dequeue
print("Reversing the deque: ")
DoubleEnded.reverse()
print (DoubleEnded)

執行上面範例程式碼,得到以下結果 -

deque(['Mon', 'Tue', 'Wed'])
Adding to the right: 
deque(['Mon', 'Tue', 'Wed', 'Thu'])
Adding to the left: 
deque(['Sun', 'Mon', 'Tue', 'Wed', 'Thu'])
Removing from the right: 
deque(['Sun', 'Mon', 'Tue', 'Wed'])
Removing from the left: 
deque(['Mon', 'Tue', 'Wed'])
Reversing the deque: 
deque(['Wed', 'Tue', 'Mon'])