保存最后N个元素(collections.deque)

1、deque(maxlen=N)创建一个固定长度的队列,当有新的记录加入而队列已经满时,会自动移除老的记录(队列更加优雅和快速)

 1 from collections import deque
 2 q = deque(maxlen=3)
 3 q.append(1)
 4 q.append(2)
 5 q.append(3)
 6 q
 7 deque([1, 2, 3], maxlen=3)
 8 q.append(4)
 9 q
10 deque([2, 3, 4], maxlen=3)

 

2、找到最大或者最小的N个元素:heapq模块中的两个函数nlargest()nsmallest()

import heapq
nums = [1,5,6,458,6,787,5,45,6]
print(heapq.nlargest(3,nums))
[787, 458, 45]
print(heapq.nsmallest(3,nums))
[1, 5, 5]

 

posted @ 2018-07-14 23:10  iqunqunqun  阅读(334)  评论(0编辑  收藏  举报