每天CookBook之Python-003

使用heapq获取最大N项和最小N项

>>> import heapq
>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
>>> print heapq.nlargest(3, nums)
[42, 37, 23]
>>> print heapq.nsmallest(3, nums)
[-4, 1, 2]
posted @ 2016-07-04 18:15  4Thing  阅读(89)  评论(0编辑  收藏  举报