亚洲免费在线-亚洲免费在线播放-亚洲免费在线观看-亚洲免费在线观看视频-亚洲免费在线看-亚洲免费在线视频

【Python練習圣典】heapq高級應用

系統 1565 0

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

            
              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]


            
          

也支持其他參數支持更為復雜的數據結構

            
              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與對象數量相差較大,則用nlargest和nsmaalest效率才高,否則先sorted再切片即可:

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

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

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

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

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

In [1]: import heapq as hq
In [2]: import numpy as np
In [3]: data = np.arange(10)
#將生成的數據隨機打亂順序
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庫的heappush函數將數據堆入
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)將數組堆中的最小元素彈出

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

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

3、heapify(heap) 將heap屬性強制應用到任意一個列表

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

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中剩下的兩個函數nlargest(n.iter)和nsmallest(n.iter)分別用來尋找任何可迭代的對象iter中第n大或者第n小的元素。可以通過使用排序(sorted函數)和分片進行完成。

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

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

2.實現一個隊列,該隊列按給定的優先級對元素進行排序,并使pop操作始終返回每個優先級最高的元素

            
              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)會按item1

其中,優先級前加負號可讓堆有優先級從高到低排序。index用于處理優先級一樣的元素。

index的另一個作用是避免優先級和index一樣時(因為index不可能相同),比較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()

因為我們并未定義Item的比較操作,所以會報如上錯誤

應用實例:

>>> 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')


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

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

【本文對您有幫助就好】

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

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 97精品福利视频在线 | 露脸真实国产精品自在 | 国产成人综合在线视频 | 久久精品国产400部免费看 | 欧美精品99| 亚洲视频国产视频 | 亚洲综合色色图 | 国产亚洲精品精品国产亚洲综合 | 日韩免费高清一级毛片在线 | 欧美国产综合日韩一区二区 | 欧美激情在线精品一区二区 | 日日操天天射 | 尹人久久| 国产一区二区在线 |播放 | 99国产成人高清在线视频 | www.男人天堂.com | 色综合啪啪 | 少妇美女极品美軳人人体 | 久久国产免费观看精品 | 在线观看国产一区二区三区 | 欧美观看一级毛片 | 草免费视频 | 性欧美video另类3d | 亚洲精品在线视频 | 亚洲精品在线视频 | 精品欧美一区二区三区在线观看 | 免费看又爽又黄禁片视频1000 | 国产在线精品福利大全 | 久热草 | 欧美一级二级aaa免费视频 | 免费尤物视频 | 热久久亚洲 | 黄在线免费看 | 国产100页 | 96精品视频在线播放免费观看 | 久久精品国产亚洲高清 | 澳门成人免费永久视频 | 香蕉九九 | 女人牲交视频一级毛片 | 夜夜艹日日干 | 欧美人成在线 |