Python3_Cookbook_最大(?。┰丶皟?yōu)先堆棧2018-09-08

找出最大或最小的N個(gè)元素##堆堆

import heapq
nums = [1,8,2,23,7,-4,19,23,42,37,2]

print (heapq.nlargest(3,nums))##最大的三個(gè)數(shù),

print (heapq.nsmallest(2,nums))##最小的兩個(gè)數(shù)

這兩個(gè)函數(shù)都可以接受一個(gè)參數(shù)哦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)###找最小值

實(shí)現(xiàn)優(yōu)先隊(duì)列###

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]

實(shí)例##

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##

print ("q._queue::::\n",q._queue)

拓展閱讀:

請(qǐng)參看:
https://www.cnblogs.com/Joyce-song94/p/7149440.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容