问题
怎样从一个集合中获得最大或者最小的 N 个元素列表?
解决方案
heapq 模块有两个函数:nlargest() 和 nsmallest() 可以完美解决这个问题。
# -*- coding:utf-8 -*-
import heapq
numbers = [1, 9, 23, 100, 49, 4, -8, 36]
max_3 = heapq.nlargest(3, numbers)
min_3 = heapq.nsmallest(4, numbers)
print('最大的3个值:', max_3)
print('最小的4个值:', min_3)
最大的3个值: [100, 49, 36]
最小的4个值: [-8, 1, 4, 9]
两个函数都能接受一个关键字参数,指定比较的元素,用于更复杂的数据结构中:
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(2, portfolio, key = lambda x: x['price'])
expensive = heapq.nlargest(2, portfolio, key = lambda x: x['price'])
print(cheap)
print(expensive)
[{'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'FB', 'shares': 200, 'price': 21.09}]
[{'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'ACME', 'shares': 75, 'price': 115.65}]
讨论
这些函数提供了很好的性能。 因为在底层实现里面,首先会先将集合数据进行堆排序后放入一个列表中:
numbers = [1, 9, 23, 100, 49, 4, -8, 36]
heapq.heapify(numbers)
print(numbers)
[-8, 9, 1, 36, 49, 4, 23, 100]
堆数据结构最重要的特征是 heap[0]永远是最小的元素。并且剩余的元素可以很容易的通过调用 heapq.heappop() 方法得到, 该方法会先将第一个元素弹出来,然后用下一个最小的元素来取代被弹出元素。
print(heapq.heappop(numbers))
print(heapq.heappop(numbers))
print(heapq.heappop(numbers))
-8
1
4
当要查找的元素个数相对(集合元素个数)比较小的时候,函数 nlargest() 和 nsmallest() 是很合适的。
如果要查找唯一的最小或最大元素,使用 min() 和 max() 函数会更快些。
如果 N 的大小和集合大小接近时,通常先排序这个集合,然后再使用切片操作会更快点 。