淘先锋技术网

首页 1 2 3 4 5 6 7

除了直接排序,还可以利用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