heapq 模块:nlargest()和nsmallest()可以完美解决这个问题。
import heapqnums = [1, 2, 3, 5, -4]print(heapq.nlargest(3, nums)) # [5, 3, 2]print(heapq.nsmallest(3, nums)) # [-4, 1, 2]
两函数能接受一个关键字参数,用于更复杂的数据结构中:
import heapqstocks = [{"name": "IBM", "shares": 100, "price": 91.1},{"name": "AAPL", "shares": 50, "price": 543.2},{"name": "FB", "shares": 200, "price": 21.09},{"name": "HPQ", "shares": 35, "price": 31.75},{"name": "YHOO", "shares": 45, "price": 16.35}]cheaps = heapq.nsmallest(3, stocks, key=lambda s: s["price"]) # 会以prcie的值进行比较expensives = heapq.nlargest(3, stocks, key=lambda s: s["price"])
