使用内置的heapd模块 In [1]: import heapq In [2]: nums = [1,8, 2, 23, 7, -4, 18, 23, 42, 37, 2] In [3]: print(heapq.nlargest(2,nums)) [42, 37] In [4]: print(heapq.nlargest(5,nums)) [42, 37, 23, 23, 18] In [5]: print(heapq.nsmallest(5,nums)) [-4, 1, 2, 2, 7]…