Python_cookbook 发表于 2018-07-25 | 分类于 Python | 评论数: | 阅读次数: 解决方案 12345678from collections import deque#deque(maxlen=N)创建一个固定长度的队列#当有新记录加入而队列已满时会自动移除最老的那条记录q = deque(maxlen=3)q.appendleft()q.popleft()#创建无限序列q = deque() 123456789101112131415#寻找集合中最大或最小的N个元素# nlargest(),nsmallest()import heapqnums=[1,8,2,23,7,-4,18,23,42,37,2]print(heapq.nlargest(3,nums)) #print [42,37,23]#将集合转换为堆,堆的特性为heap[0]总是最小的那个元素nums=[1,8,2,23,7,-4,18,23,42,37,2]import heapqheap = list(nums)heapq.heapify(heap)#去除heap中最小值heap.heappop(heap)#插入元素heap.heappush() 喜欢的可以对我打赏了哟~ 打赏 微信支付 支付宝