方案一:
nlargest 和 nsmallest
from heapq import nlargest, nsamllest nums = [1, 8, 2, 23, 7, -4, 18, 23, 42] print(nlargest(3, nums)) print(nsmallest(3, nums))
这两个函数都可以接受一个key,
portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22} ] cheap = nsmallest(3, portfolio, key=lambda s: s['price']) expensive = nlargest(3, portfolio, key=lambda s: s['price'])
如果n = 1:
使用 min 和 max 更加的快,如果 n 的大小和 序列的长度差不多时,使用 sort 排序,然后切片会更加合适。