上一篇文章: Python实用技法第2篇:使用deque保留最新的N个元素
下一篇文章: Python实用技法第4篇:实现优先级队列
咱们想在某个集合中找出最大或最小的N个元素
heapq模块中有两个函数:nlargest()和nsmallest()
代码:segmentfault
import heapq nums=[1,444,66,77,34,67,2,6,8,2,4,9,556] print(heapq.nlargest(3,nums)) print(heapq.nsmallest(3,nums))
结果:数据结构
[556, 444, 77] [1, 2, 2]
这个两个函数均可以接受一个参数key,从而容许他们能够工做在更加复杂的数据结构上:函数
代码:code
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}, ] cheap=heapq.nsmallest(3,portfolio,key=lambda s:s['price']) expensive=heapq.nlargest(3,portfolio,key=lambda s:s['price']) print(cheap) print(expensive)
结果:队列
[{'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}] [{'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}]
若是只是简单的查找最小或者最大的元素(N=1),那么使用min()和max()会更快。
上一篇文章: Python实用技法第2篇:使用deque保留最新的N个元素
下一篇文章: Python实用技法第4篇:实现优先级队列