1. 程式人生 > 其它 >python雙向佇列deque實踐與總結

python雙向佇列deque實踐與總結

背景

1.什麼是雙端佇列

deque的英文意思是Double-Ended Queue,deque是為了在兩端高效實現插入和刪除操作的雙向列表,適合用於佇列和棧:deque除了實現list的append()和pop()外,還支援appendleft()和popleft(),這樣就可以非常高效地往頭部或者尾部新增或刪除元素

基本概念

與常見的list使用區別如下所示


常用的介面

deque:append和popleft

Deque基本表現

  • 優點

(1)deque接收GIL管理,執行緒安全。list沒有GIL鎖,所以執行緒不安全。也就是說,在併發場景中,list可能會導致一致性問題,而deque不會。

(2)deque支援固定長度。當長度滿了,當我們繼續使用append時,它會自動彈出最早插入的資料。
(3) deque 更快

deque demo

See the following code example of Deque in Python.


#importing deque from collections module
from collections import deque

#initializing the deque object
deq = deque(['apple', 'mango', 'orange'])
#printing the initial deque object 
print("Printing the initial deque object items \n" , deq, '\n')
#append(x) demonstration
print("Appending a new element to the right of deque")
deq.append('papaya')
print(deq , '\n') 
#appendleft(x) demonstration
print("Appending a new element to the left of deque")
deq.appendleft('strawberry')
print(deq , '\n') 
#count(x) demonstration
print("Counting the the occurrence of apple in deque")
print(deq.count('apple') , '\n') 
#extend(iterable) demonstration
deq.extend(['grapes', 'watermelon'])
print("Extending the deque with new items on the right")
print(deq, "\n") 
extendleft(iterable) demonstration
deq.extendleft(['pear', 'guava'])
print("Extending the deque with new items on the left")
print(deq, "\n") 
#index(x [, start [, stop]]) demonstration
print("Finding the index of an item")
print(deq.index('strawberry'), "\n") 
#insert(i,x) demonstration
print("Inserting an item to the deque by specifiying the index")
deq.insert(2,'banana')
print(deq, "\n") 
#pop() demonstration
print("Popping out last item from the right")
print(deq.pop(), "\n") 
#popleft() demonstration
print("Popping out first item from the left")
print(deq.popleft(), "\n") 
#remove() demonstration
print("Removing an item from the deque")
deq.remove("apple")
print(deq, "\n") 

執行結果:


Printing the initial deque object items
deque(['apple', 'mango', 'orange'])

Appending a new element to the right of deque
deque(['apple', 'mango', 'orange', 'papaya'])

Appending a new element to the left of deque
deque(['strawberry', 'apple', 'mango', 'orange', 'papaya'])

Counting the the occurrence of apple in deque
1

Extending the deque with new items on the right
deque(['strawberry', 'apple', 'mango', 'orange', 'papaya', 'grapes', 'watermelon'])

Extending the deque with new items on the left
deque(['guava', 'pear', 'strawberry', 'apple', 'mango', 'orange', 'papaya', 'grapes', 'watermelon'])

Finding the index of an item
2

Inserting an item to the deque by specifiying the index
deque(['guava', 'pear', 'banana', 'strawberry', 'apple', 'mango', 'orange', 'papaya', 'grapes', 'watermelon'])

Popping out last item from the right
watermelon

Popping out first item from the left
guava

Removing an item from the deque
deque(['pear', 'banana', 'strawberry', 'mango', 'orange', 'papaya', 'grapes'])

總結

如果需要使用一個容器來處理資料 請使用deque