PythonCookBook chapter-01-队列deque

队列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')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值