PythonCookBook chapter-01-佇列deque
阿新 • • 發佈:2018-12-19
佇列deque(python3)
from
collections
import
deque
deque的方法可以用help(deque)檢視
1,建立無界限佇列
2,建立定長佇列
3,利用佇列儲存匹配行
注:編寫搜尋某項記錄的程式碼時,通常會用到含有yield關鍵字的生成器函式。yield使用淺析可以參考點選開啟連結
from collections import deque def my_search(lines, pattern): # 獲取文字中含有某個欄位的行 for line in lines: if pattern in line: yield line if __name__ == '__main__': try: with open('somefile.txt', 'r') as fObj: result = deque(maxlen=3) for line in my_search(fObj, 'python'): result.append(line) print(result) except: pass
輸出:
deque(['to python\n', 'you python\n', 'sdfsdfsdf python'], maxlen=3)
4,heapq模組的使用
import heapq
通過help(heapq)可看到heapq的方法,使用方法可參考點選開啟連結
4.1,找到最大或最小的N個元素,merge兩個列表
4.2 實現優先順序佇列>>> list1 = [2,3,3,8,9] >>> print(heapq.nlargest(2,list1)) [9, 8] >>> print(heapq.nsmallest(2,list1)) [2, 3] >>> for i in heapq.merge(list1, [5,4,8]): print(i, end=',') 2,3,3,5,4,8,8,9, >>>
import heapq class PriorityQueue: #優先順序佇列 def __init__(self): self._queue = [] self._index = 0 def push(self, item, priority): # heapq的堆是小頂堆,priority取負是為了heappop得到的總是最小的元素 heapq.heappush(self._queue, (-priority, self._index, item)) self._index += 1 def pop(self): # [-1]返回item物件 return heapq.heappop(self._queue)[-1] def print(self): # 列印這個佇列 for i in self._queue: print(i, end='\n') class Item: def __init__(self, name): self.name = name def __repr__(self): return 'Item({!r})'.format(self.name) q = PriorityQueue() q.push(Item('foo1'), 1) q.push(Item('foo4'), 4) q.push(Item('foo5'), 5) q.push(Item('foo2'), 2) q.push(Item('foo3'), 3) q.push(Item('foo11'), 1) q.push(Item('foo55'), 5) q.print() print('-----pop----') print(q.pop()) print(q.pop()) print(q.pop()) print(q.pop()) print(q.pop()) print(q.pop()) print(q.pop())
輸出:
(-5, 2, Item('foo5'))
(-3, 4, Item('foo3'))
(-5, 6, Item('foo55'))
(-1, 0, Item('foo1'))
(-2, 3, Item('foo2'))
(-1, 5, Item('foo11'))
(-4, 1, Item('foo4'))
-----pop----
Item('foo5')
Item('foo55')
Item('foo4')
Item('foo3')
Item('foo2')
Item('foo1')
Item('foo11')