艺赛旗 RPA9.0全新首发免费下载 点击下载
http://www.i-search.com.cn/index.html?from=line1
问题
我们想在某个集合中找出最大或最小的 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’: ‘IBM’, ‘shares’: 100, ‘price’: 135.79},
{‘name’: ‘AAPL’, ‘shares’: 50, ‘price’: 208.97},
{‘name’: ‘FB’, ‘shares’: 200, ‘price’: 188.45},
{‘name’: ‘HPQ’, ‘shares’: 35, ‘price’: 19.54},
{‘name’: ‘INTC’, ‘shares’: 45, ‘price’: 46.84},
{‘name’: ‘AMZN’, ‘shares’: 75, ‘price’: 1824.34}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s[‘price’])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s[‘price’])
高级用法