队列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两个列表
>>> 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,
>>>
4.2 实现优先级队列
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')