日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

【Python練習(xí)圣典】heapq高級(jí)應(yīng)用

系統(tǒng) 1887 0

1.從集合中取出最大或最小N個(gè)元素

            
              import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums)) # 輸出 [42, 37, 23]
print(heapq.nsmallest(3, nums)) # 輸出 [-4, 1, 2]


            
          

也支持其他參數(shù)支持更為復(fù)雜的數(shù)據(jù)結(jié)構(gòu)

            
              portfolio = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', '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'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
            
          

?

?如果N與對(duì)象數(shù)量相差較大,則用nlargest和nsmaalest效率才高,否則先sorted再切片即可:

            
              sorted(items)[:N] 
sorted(items)[-N:]
            
          

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

補(bǔ)充heapq的其他常見函數(shù)說(shuō)明 :(引自:https://blog.csdn.net/brucewong0516/article/details/79042839)

數(shù)據(jù)結(jié)構(gòu)堆(heap)是一種優(yōu)先隊(duì)列。使用優(yōu)先隊(duì)列能夠以任意順序增加對(duì)象,并且能在任意的時(shí)間(可能在增加對(duì)象的同時(shí))找到(也可能移除)最小的元素,也就是說(shuō)它比python的min方法更加有效率。

1、heappush(heap,n)數(shù)據(jù)堆入

In [1]: import heapq as hq
In [2]: import numpy as np
In [3]: data = np.arange(10)
#將生成的數(shù)據(jù)隨機(jī)打亂順序
In [4]: np.random.shuffle(data)
In [5]: data
Out[5]: array([5, 8, 6, 3, 4, 7, 0, 1, 2, 9])
#定義heap列表
In [6]: heap = []
#使用heapq庫(kù)的heappush函數(shù)將數(shù)據(jù)堆入
In [7]: for i in data:
? ?...: ? ? hq.heappush(heap,i)
? ?...:
In [8]: heap
Out[8]: [0, 1, 3, 2, 5, 7, 6, 8, 4, 9]

In [9]: hq.heappush(heap,0.5)
In [10]: heap
Out[10]: [0, 0.5, 3, 2, 1, 7, 6, 8, 4, 9, 5]

2、heappop(heap)將數(shù)組堆中的最小元素彈出

In [11]: hq.heappop(heap)
Out[11]: 0

In [12]: hq.heappop(heap)
Out[12]: 0.5

3、heapify(heap) 將heap屬性強(qiáng)制應(yīng)用到任意一個(gè)列表

heapify 函數(shù)將使用任意列表作為參數(shù),并且盡可能少的移位操作,,將其轉(zhuǎn)化為合法的堆。如果沒有建立堆,那么在使用heappush和heappop前應(yīng)該使用該函數(shù)。

In [13]: heap = [5,8,0,3,6,7,9,1,4,2]

In [14]: hq.heapify(heap)

In [15]: heap
Out[15]: [0, 1, 5, 3, 2, 7, 9, 8, 4, 6]

4、heapreplace(heap,n)彈出最小的元素被n替代

In [17]: hq.heapreplace(heap,0.5)
Out[17]: 0

In [18]: heap
Out[18]: [0.5, 1, 5, 3, 2, 7, 9, 8, 4, 6]

5、nlargest(n,iter)、nsmallest(n,iter)
heapq中剩下的兩個(gè)函數(shù)nlargest(n.iter)和nsmallest(n.iter)分別用來(lái)尋找任何可迭代的對(duì)象iter中第n大或者第n小的元素??梢酝ㄟ^使用排序(sorted函數(shù))和分片進(jìn)行完成。

#返回第一個(gè)最大的數(shù)
In [19]: hq.nlargest(1,heap)
Out[19]: [9]
#返回第一個(gè)最小的數(shù)
In [20]: hq.nsmallest(1,heap)
Out[20]: [0.5]
————————————————
版權(quán)聲明:本文為CSDN博主「brucewong0516」的原創(chuàng)文章,遵循 CC 4.0 BY-SA 版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/brucewong0516/article/details/79042839

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

2.實(shí)現(xiàn)一個(gè)隊(duì)列,該隊(duì)列按給定的優(yōu)先級(jí)對(duì)元素進(jìn)行排序,并使pop操作始終返回每個(gè)優(yōu)先級(jí)最高的元素

            
              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]
            
          

heapq.heappush(queue,item)會(huì)按item1

其中,優(yōu)先級(jí)前加負(fù)號(hào)可讓堆有優(yōu)先級(jí)從高到低排序。index用于處理優(yōu)先級(jí)一樣的元素。

index的另一個(gè)作用是避免優(yōu)先級(jí)和index一樣時(shí)(因?yàn)閕ndex不可能相同),比較item:

>>> a = (1, Item('foo'))
>>> b = (5, Item('bar'))
>>> a < b
True
>>> c = (1, Item('grok'))
>>> a < c
Traceback (most recent call last):
File " ", line 1, in
TypeError: unorderable types: Item() < Item()

因?yàn)槲覀儾⑽炊xItem的比較操作,所以會(huì)報(bào)如上錯(cuò)誤

應(yīng)用實(shí)例:

>>> class Item:
...? ? ?def __init__(self, name):
... ? ? ? ?self.name = name
... ? ?def __repr__(self):
... ? ? ? ? return 'Item({!r})'.format(self.name)
...
>>> q = PriorityQueue()
>>> q.push(Item('foo'), 1)
>>> q.push(Item('bar'), 5)
>>> q.push(Item('spam'), 4)
>>> q.push(Item('grok'), 1)
>>> q.pop()
Item('bar')
>>> q.pop()
Item('spam')
>>> q.pop()
Item('foo')
>>> q.pop()
Item('grok')


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對(duì)您有幫助就好】

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長(zhǎng)會(huì)非常 感謝您的哦!!!

發(fā)表我的評(píng)論
最新評(píng)論 總共0條評(píng)論
主站蜘蛛池模板: 岳池县| 双城市| 锡林郭勒盟| 玛多县| 休宁县| 郓城县| 昌邑市| 大洼县| 芮城县| 莎车县| 武宁县| 呼伦贝尔市| 敦化市| 抚远县| 临沧市| 栾川县| 西丰县| 靖江市| 大名县| 宁都县| 离岛区| 大同市| 九龙坡区| 自贡市| 伊宁市| 石阡县| 玛多县| 磐石市| 新民市| 丽水市| 吴江市| 梨树县| 邮箱| 宁武县| 英吉沙县| 马尔康县| 蒲江县| 琼海市| 宿州市| 太白县| 沐川县|