python3 deque(雙向隊列)


轉載:https://www.cnblogs.com/zhenwei66/p/6598996.html

 

創建雙向隊列

import collections
d = collections.deque()

append(往右邊添加一個元素)

復制代碼
import collections
d = collections.deque()
d.append(1)
d.append(2)
print(d)

#輸出:deque([1, 2])
復制代碼

appendleft(往左邊添加一個元素)

復制代碼
import collections
d = collections.deque()
d.append(1)
d.appendleft(2)
print(d)

#輸出:deque([2, 1])
復制代碼

clear(清空隊列)

復制代碼
import collections
d = collections.deque()
d.append(1)
d.clear()
print(d)

#輸出:deque([])
復制代碼

copy(淺拷貝)

復制代碼
import collections
d = collections.deque()
d.append(1)
new_d = d.copy()
print(new_d)

#輸出:deque([1])
復制代碼

count(返回指定元素的出現次數)

復制代碼
import collections
d = collections.deque()
d.append(1)
d.append(1)
print(d.count(1))

#輸出:2
復制代碼

extend(從隊列右邊擴展一個列表的元素)

復制代碼
import collections
d = collections.deque()
d.append(1)
d.extend([3,4,5])
print(d)

#輸出:deque([1, 3, 4, 5])
復制代碼

extendleft(從隊列左邊擴展一個列表的元素)

復制代碼
import collections
d = collections.deque()
d.append(1)
d.extendleft([3,4,5])
print(d)
#
# #輸出:deque([5, 4, 3, 1])
復制代碼

index(查找某個元素的索引位置)

復制代碼
import collections
d = collections.deque()
d.extend(['a','b','c','d','e'])
print(d)
print(d.index('e'))
print(d.index('c',0,3))  #指定查找區間

#輸出:deque(['a', 'b', 'c', 'd', 'e'])
#     4
#     2
復制代碼

insert(在指定位置插入元素)

復制代碼
import collections
d = collections.deque()
d.extend(['a','b','c','d','e'])
d.insert(2,'z')
print(d)

#輸出:deque(['a', 'b', 'z', 'c', 'd', 'e'])
復制代碼

pop(獲取最右邊一個元素,並在隊列中刪除)

復制代碼
import collections
d = collections.deque()
d.extend(['a','b','c','d','e'])
x = d.pop()
print(x,d)

#輸出:e deque(['a', 'b', 'c', 'd'])
復制代碼

popleft(獲取最左邊一個元素,並在隊列中刪除)

復制代碼
import collections
d = collections.deque()
d.extend(['a','b','c','d','e'])
x = d.popleft()
print(x,d)

#輸出:a deque(['b', 'c', 'd', 'e'])
復制代碼

remove(刪除指定元素)

復制代碼
import collections
d = collections.deque()
d.extend(['a','b','c','d','e'])
d.remove('c')
print(d)

#輸出:deque(['a', 'b', 'd', 'e'])
復制代碼

reverse(隊列反轉)

復制代碼
import collections
d = collections.deque()
d.extend(['a','b','c','d','e'])
d.reverse()
print(d)

#輸出:deque(['e', 'd', 'c', 'b', 'a'])
復制代碼

rotate(把右邊元素放到左邊)

復制代碼
import collections
d = collections.deque()
d.extend(['a','b','c','d','e'])
d.rotate(2)   #指定次數,默認1次
print(d)

#輸出:deque(['d', 'e', 'a', 'b', 'c'])
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM