# collections 的deque 所有用法 python collection雜談之三 4. deque 一般來說作為串列容器,list就可以應付很多狀況,但還是有一些狀況list效能是不理想的,比如說如果要在list的head端做push和pop的動作,其所消耗的時間複雜度是O(n),也就是他在時間上並不有效支援雙端的push和pop操作,而當我們有這個需求的時候,deque(double-end queue)就是一個不錯的選擇: ## deque 常用方法 ```python= # deque 的isEmpty() 方法 If d is your deque, use if d: # not empty else: # empty ``` ## 新增部分: ```python= ## 新增element 記得也有左右邊 分別代表stack 和queue append(item): Add an item to the right end. appendleft(item): Add an item to the left end. ``` ## 取出部分:記得d.popleft() 才是取串列前面的元素 才是queue 如果是stack 就是pop() ```python= ` >>> from collections import deque >>> d = deque('123456789') >>> d deque(['1', '2', '3', '4', '5', '6', '7', '8', '9']) >>> d.pop() # 提取左邊元素 '9' >>> d deque(['1', '2', '3', '4', '5', '6', '7', '8']) >>> d.popleft() # 提取右邊元素 '1' ```