0.摘要
本文主要介绍heapq模块提供的主要函数方法。
1.nlargest()和nsmallest
从字面意思就可以知道
heapq.nlargest(n, iterable, key=None) :返回可枚举对象中的 n 个最大值
heapq.nsmallest(n, iterable, key=None) :返回可枚举对象中的 n 个最小值。
import heapq
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(heapq.nlargest(3,nums))
print(heapq.nsmallest(3,nums))
#result:[9, 8, 7]
#result:[0, 1, 2]
相比于max()和min()函数,nlargest()和nsmallest()能够按递增或递减顺序给出最大或最小的n个值。
另外,nlargest()和nsmallest()更强大的地方在于能够接受一个参数key,从而允许了这两个函数能够工作在更为复杂的数据结构上。
import heapq
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'pr