Python数据结构 - 利用headp模块寻找最大N个元素并实现优先队列

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

猜你喜欢

转载自www.cnblogs.com/Tony100K/p/11625653.html