上一篇文章: 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篇:實現優先級隊列