解决方案:
heapq 模块有两个函数:nlargest() 和 nsmallest() 可以完美解决这个问题。
import heapq nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] print(heapq.nlargest(3, nums)) # Prints [42, 37, 23] print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]
|
屌丝程序猿
努力学python的屌丝. |
heapq 模块有两个函数:nlargest() 和 nsmallest() 可以完美解决这个问题。
import heapq nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] print(heapq.nlargest(3, nums)) # Prints [42, 37, 23] print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]