问题
我们想在某个集合中找出最大或最小的N个元素
解决方案
heapq模块中有两个函数nlargest()
和nsmallest()
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]
这两个函数都可以接收一个参数key,从而允许它们工作在更加复杂的数据结构之上
portfolio = [
{'name': 'yy', 'shares': 100, 'price': 91.1},
{'name': 'zz', 'shares': 50, 'price': 543.22},
{'name': 'xq', 'shares': 200, 'price': 21.09},
{'name': 'wz', 'shares': 35, 'price': 31.75},
{'name': 'app', 'shares': 45, 'price': 16.35},
{'name': 'mm', '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'])