找出最大或最小的N个元素##堆堆
import heapq
nums = [1,8,2,23,7,-4,19,23,42,37,2]
print (heapq.nlargest(3,nums))##最大的三个数,
print (heapq.nsmallest(2,nums))##最小的两个数
这两个函数都可以接受一个参数哦key
portfolio = [
{'name':'IBM','shares':100,'price':91.1},
{'name':'APPL','shares':50,'price':543.22},
{'name':'FB','shares':200,'price':21.09},
{'name':'HPQ','shares':35,'price':31.75},
{'name':'YHOO','shares':45,'price':16.35},
{'name':'ACME','shares':75,'price':115.65}
]
cheap = heapq.nsmallest(3,portfolio,key=lambda s: s['price'])
print ("cheap:\n",cheap)
expensive = heapq.nlargest(3,portfolio,key=lambda s: s['price'])
print ("expensive :\n",expensive)
heap = list(nums)
heapq.heapify(heap)
heapq.heappop(heap)###找最小值
实现优先队列###
import heapq
class PriorityQueue:
def init(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
实例##
class Item :
def init(self,name):
self.name = name
def repr(self) :
return 'Item({!r})'.format(self.name)
""""
example = Item('foo')
print ("Class ,Item:\n",example.repr())###Priori see object of Item####
"""
q = PriorityQueue()
q.push(Item('foo'),1)
q.push(Item('bar'),5)
q.push(Item('spam'),4)
q.push(Item('grok'),1)
print ("all:",q._queue)#all: [(-5, 1, Item('bar')), (-1, 0, Item('foo')), (-4, 2, Item('spam')), (-1, 3, Item('grok'))]
print (q.pop())###bar
print (q.pop())###spam
print (q.pop())##foo
print (q.pop())###grok##