02-固定长度队列-取最大或者最小的N个成员

保留最后N位

保留N

利用collections 的 deque() 函数 制作一个固定大小的‘队列’ 可以使用append方法

当有新的队员加入同时已经满了的时候,最老的元素就会剔除(模拟队列)

from collections import deque


def search(lines, pattern, history=5):
    keep_lines = deque(maxlen=history)
    for i in lines:
        if pattern in i:
            keep_lines.append(i)
    yield keep_lines


if __name__ == '__main__':
    with open('1.txt', mode='r+', encoding='utf-8') as f:
        for keep_lines in search(f, 'python', 5):
            print(keep_lines)
            
# 1.txt
"""
111111111111python
211111111111python
311111111111python
411111111111python
511111111111python
611111111111python
711111111111python
811111111111python
911111111111python
101111111111python
"""

deque()

简单数据队列结构

在队列的两边插入删除的时间复杂度位O(1), 而在列表的两边删除插入的复杂度为O(N)

deq = deque()  # deq 是一个可迭代对象
# 最后添加
deq.append(1)
deq.append(2)
deq.append(3)
# 前面添加
deq.appendleft(4)

print(deq)
# 移除最后
deq.pop()
print(deq)

# 移除最前
deq.popleft()
print(deq)

从一个列表中获取最大或者最小的N个元素

heapq模块

import heapq
l = [1,5,2,5,7,18,3,4,32,6,17]
print(heapq.nsmallest(3, l))
print(heapq.nlargest(3, l))

dic = [
    {'name': 'li_yao', 'age': 25},
    {'name': 'bob', 'age': 16},
    {'name': 'mike', 'age': 35},
    {'name': 'mary', 'age': 12},
    {'name': 'lucy', 'age': 28},
    {'name': 'gary', 'age': 19},
]

# item 已经是里面的dic成员
print(heapq.nsmallest(2, dic, key=lambda item: item['age']))
print(heapq.nlargest(2, dic, key=lambda item: item['age']))
posted @ 2018-12-06 23:44  一如少年模样  阅读(288)  评论(0编辑  收藏  举报