heapq 模块有两个函数:nlargest() 和 nsmallest() 可以完美解决这个问题。
nlargest()
nsmallest()
import heapq nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] print(heapq.nlargest(3, nums)) # Prints [42, 37, 23] print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]