0%

Python 查找最大或最小的N个元素

除了直接排序,还可以利用heaq模块的nlargest()nsmallest()方法,例如:

1
2
3
4
5
6
7
>>> 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]