天天看點

從python清單中找到最大的或最小的N個元素

heapq子產品中有兩個函數,nlargest()和nsmallest()兩個方法,可以分别找出最大或最小的N個數。

import heapq
l1 = [11,22,54545,23,54,76,7343,345]
print(heapq.nlargest(3,l1))
print(heapq.nsmallest(4,l1))
輸出:
[54545, 7343, 345]
[11, 22, 23, 54]