Python輕鬆入門-34 列表查詢最大和最小值
阿新 • • 發佈:2019-02-11
視訊教程下載連結:http://pan.baidu.com/s/1kVuNFx1 配套教程下載:http://pan.baidu.com/s/1qYdI6q4 這節課,我們來教大家如何獲得列表的最大最小值,你可能會說,我直接用sorted排序函式不就可以了,排序之後去除掉首尾的元素不就可以獲得最大值了嗎?但是這種情況僅適用於純數字或者純字串,那麼假如有一個員工的物件,它有工作id,姓名,工資等屬性,那麼該如何排序呢?這裡就需要引入heapq模組,Python中的heapq模組提供了一種堆佇列heapq型別,這樣實現堆排序等演算法就相當方便,這裡我們就來詳解Python中heapq模組的用法,假如現在有一個列表:
import heapq grades = [32, 43, 654, 34, 666] |
print(heapq.nlargest(3, grades)) |
stocks = [ {'ticker':'AAPL', 'price':201}, {'ticker':'GOOG', 'price':800}, {'ticker':'FB', 'price':54}, {'ticker':'MSFT', 'price':68} ] |
print(heapq.nsmallest(2, stocks, key=lambda stock: stock['price'])) |
檢視原文:http://www.oxox.work/web/python/max-min/