Python數據結構 – 利用headp模組尋找最大N個元素並實現優先隊列

  • 2019 年 10 月 5 日
  • 筆記

用headp找到最大最小的N個值

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

數據結構複雜時

可以用key這個參數,傳入一個lambda表達式

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'])    print(cheap)  print(expensive)
[{'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}]  [{'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'ACME', 'shares': 75, 'price': 115.65}, {'name': 'IBM', 'shares': 100, 'price': 91.1}]
## 當N的大小和元素差不多時,可以直接用sorted  nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]  sorted(nums,reverse=False)[-3:]  # 默認從小到大,改成True從小到大
[23, 37, 42]

也可以讓一個列表堆化

nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]  heapq.heapify(nums)  nums
[-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]
print(heapq.heappop(nums))  print(heapq.heappop(nums))  print(heapq.heappop(nums))  # 相對較大
-4  1  2

使用headp實現優先隊列

## 優先順序為負先彈出高的  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]    # Example use  class Item:      def __init__(self, name):          self.name = name      def __repr__(self):          return 'Item({!r})'.format(self.name)#tostring    q = PriorityQueue()  q.push(Item('foo'), 1)  q.push(Item('bar'), 5)  q.push(Item('spam'), 4)  q.push(Item('grok'), 1)    print("Should be bar:", q.pop())  print("Should be spam:", q.pop())  print("Should be foo:", q.pop())  print("Should be grok:", q.pop())  
Should be bar: Item('bar')  Should be spam: Item('spam')  Should be foo: Item('foo')  Should be grok: Item('grok')