Python cookbook(資料結構與演算法)儲存最後N個元素的方法,pythoncookbook

來源:互聯網
上載者:User

Python cookbook(資料結構與演算法)儲存最後N個元素的方法,pythoncookbook

本文執行個體講述了Python儲存最後N個元素的方法。分享給大家供大家參考,具體如下:

問題:希望在迭代或是其他形式的處理過程中對最後幾項記錄做一個有限的記錄統計

解決方案:選擇collections.deque。

如下的代碼對一系列文本行做簡單的文本匹配操作,當發現有匹配時就輸出當前的匹配行以及最後檢查過的N行文本:

from collections import dequedef search(lines, pattern, history=5):  previous_lines = deque(maxlen=history)  for line in lines:    if pattern in line:      yield line, previous_lines    previous_lines.append(line)# Example use on a fileif __name__ == '__main__':  with open('somefile.txt') as f:    for line, prevlines in search(f, 'python', 5):      for pline in prevlines:        print(pline, end='')      print(line, end='')      print('-'*20)

正如上面的代碼一樣,當編寫搜尋某項記錄的代碼時,通常會用到含有yield關鍵字的產生器函數,將處理搜尋過程的代碼與使用搜尋結果的代碼解耦開來。具體產生器可參考本站迭代器和產生器相關內容。

deque(maxlen=N)建立一個固定長度的隊列,當加入新元素而隊列已滿時會自動移除最老的那條記錄:

>>> from collections import deque>>> q=deque(maxlen=3)>>> q.append(1)>>> q.append(2)>>> q.append(3)>>> qdeque([1, 2, 3], maxlen=3)>>> q.append(4)>>> qdeque([2, 3, 4], maxlen=3)>>> q.append(5)>>> qdeque([3, 4, 5], maxlen=3)>>>

儘管可以在列表上手動完成這樣的操作(append、del),但隊列的這種解決方案要優雅得多,運行速度也快得多。

如果不指定隊列長度,則得到一個無界限的隊列,可在兩端執行添加和彈出操作:

>>> q=deque()>>> qdeque([])>>> q.append(1)>>> q.append(2)>>> q.append(3)>>> qdeque([1, 2, 3])>>> q.appendleft(4)>>> qdeque([4, 1, 2, 3])>>> q.pop()3>>> qdeque([4, 1, 2])>>> q.popleft()4>>> qdeque([1, 2])>>>

聯繫我們

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