屌丝程序猿
努力学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]

 

posted on 2018-06-27 15:07  越努力越幸福i  阅读(167)  评论(0)    收藏  举报