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]
原文地址:https://www.cnblogs.com/iqunqunqun/p/9311274.html
时间: 2024-10-18 20:40:01