Python實用技法第3篇:找到最大或最小的N個元素

一、需求數據結構

咱們想在某個集合中找出最大或最小的N個元素ide

二、解決方案函數

heapq模塊中有兩個函數:nlargest()和nsmallest()學習

代碼:code

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,從而容許他們能夠工做在更加複雜的數據結構上:資源

代碼:it

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)
Python資源分享qun 784758214 ,內有安裝包,PDF,學習視頻,這裏是Python學習者的彙集地,零基礎,進階,都歡迎

結果:io

[{'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()會更快。class

相關文章
相關標籤/搜索