# 1.4 查找最大或最小的N个元素

### 解决方案

heapq模块有两个函数：`nlargest()``nsmallest()`可以完美解决这个问题。

``````import heapq

nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nsmallest(3, nums))
# 输出结果：[-4, 1, 2]
print(heapq.nlargest(3, nums))
# 输出结果：[42, 37, 23]
``````

``````import heapq

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}
]
# 以price的值进行比较
cheap = heapq.nsmallest(3, portfolio, lambda s: s["price"])
print(cheap)
"""

[{"name": "YHOO", "shares": 45, "price": 16.35}, {"name": "FB", "shares": 200, "price": 21.09}, {"name": "HPQ", "shares": 35, "price": 31.75}]
"""
``````

### 讨论

``````import heapq

nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
heapq.heapify(nums)
print(nums)
"""

[-4, 2, 1, 23, 7, 2, 18, 23, 42, 37, 8]
"""
``````

``````import heapq

nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
heapq.heapify(nums)
print(heapq.heappop(nums), heapq.heappop(nums), heapq.heappop(nums))
"""

-4 1 2
"""
``````

### 总结

• 当要查找的元素个数N相对比较小的时候，函数`nlargest()``nsmallest()`是很合适的；
• 如果仅仅想要查找唯一的（N=1）最小或最大元素，那么使用函数`min()``max()`会更快些；
• 如果N的大小和集合大小接近，通常先排序再使用切片操作会更快些（`sorted(items)[:N]`或是`sorted(items)[-N:]`）。