26 python 中deque模組詳解

來源:互聯網
上載者:User

標籤:模組   pen   操作方法   標準   xtend   Python標準庫   ftp   nbsp   code   

deque模組是python標準庫collections中的一項,它提供了兩端都可以操作的序列,這意味著,在序列的前後你都可以執行添加或刪除操作。

1.建立deque序列:

from collections import dequed=deque()

2.deque提供了類似list的操作方法:

d=deque()d.append(3)d.append(8)d.append(1)

那麼此時

d=deque([3,8,1]),len(d)=3,d[0]=3,d[-1]=1

 

 

3.兩端都使用pop:

d=deque(‘12345’)

那麼

d=deque([‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘])

 

d.pop()拋出的是’5’,d.leftpop()拋出的是’1’,可見預設pop()拋出的是最後一個元素。

 

4.限制deque的長度

d=deque(maxlen=20)for i in range(30):    d.append(str(i))

此時d的值為

d=deque([‘10‘, ‘11‘, ‘12‘, ‘13‘, ‘14‘, ‘15‘, ‘16‘, ‘17‘, ‘18‘, ‘19‘, ‘20‘, ‘21‘, ‘22‘, ‘23‘, ‘24‘, ‘25‘, ‘26‘, ‘27‘, ‘28‘, ‘29‘], maxlen=20)

,可見當限制長度的deque增加超過限制數的項時,另一邊的項會自動刪除。

 

5.添加list各項到deque中:

d=deque([1,2,3,4,5])d.extend([0])

那麼此時

d=deque([1,2,3,4,5,0])

 

d.extendleft([6,7,8])

此時

d=deque([8, 7, 6, 1, 2, 3, 4, 5, 0])

 

26 python 中deque模組詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.