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])>>>