除了直接排序,还可以利用heaq模块的nlargest()和nsmallest()方法,例如:
heaq
nlargest()
nsmallest()
>>> nums = [3, 5, 2, 4, 1] >>> smallest = heapq.nsmallest(3, nums) >>> print(smallest) [1, 2, 3] >>> largest = heapq.nlargest(3, nums) >>> print(largest) [5, 4, 3]
Python Cookbook 1.4