Python之Collections內建模組詳細說明

來源:互聯網
上載者:User
collections 是 python 的內建模組,源碼位於 Lib/collections/init.py ,該模組提供了通用的資料容器。

deque 容器物件

通過 from collections import deque 引入,建立 deque 容器物件時,可通過設定參數為 Iterable 對象(如 tuple,list,str)或 maxlen=x(int類型) or None 進行初始化。

deque 容器支援安全執行緒,通過 append 或 pop 對 deque 的兩端進行插入或移除元素時,時間複雜度為 O(1)。與 list 對象相比,list 同樣有相同的 api 實現相同的功能,但是對於 pop(0) 或 insert(0, x) 等對 list 的操作,時間複雜度為 O(n)。

如果在初始化 deque 時未聲明 maxlen 或聲明 maxlen=None,那麼 deque 容器可以容納任意多的元素,否則, deque 容器會被定義為有限長度的元素容器。

一旦容器中的元素個數達到設定的 maxlen,當有新的元素加入時,則會在加入元素一端的另一端排除相同個數的元素,這樣可以保證當前 deque 中的元素全部是最新加入的元素。

deque 對象函數

append(x)

appendleft(x)

clear()

copy()

count(x):返回容器中值為 x 的元素個數

extend(iterable)

extendleft(iterable)

index(x):在容器中查到第一個值為 x 的元素索引,如果不存在,拋起 ValueError 異常

insert(idx, x)

pop()

popleft()

remove(x)

reverse():翻轉容器中的元素,並返回 None

rotate(n)

deque 對象唯讀屬性

maxlen

除了上述的對象函數外,由於 deque 對象也是 Iterable 對象,那麼 len(deque);reversed(deque);copy.copy(deque);copy.deepcopy(deque) 等函數同樣起作用,同樣 in 操作符也在遍曆 deque 操作時使用,切片操作 deque[-1] 也可以返回容器中最後一個元素。如果對容器中的隨機元素進行操作的話,建議使用 list。

demo

擷取檔案中的 python 字串所在的一行內容,和這行內容的前三行

from collections import dequedef search(lines, pattern, maxlen):    pre_lines = deque(maxlen=maxlen)    for line in lines:        if pattern in line:            yield line, pre_lines        pre_lines.append(line)if name == 'main':    with(open('./test.txt')) as f:        for line, pre_lines in search(f, 'python', 3):            for pre_line in pre_lines:                print(pre_line, end='')            print(line)

輸入文字檔內容為

c#cc++javascriptpythonjavadelphipythongolangperlcsshtmlpython

通過代碼輸出為

cc++javascriptpythonpythonjavadelphipythonperlcsshtmlpython

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.