Python用于取top N的模块——heapq

Python有一个专门用于取前几大或前几小的模块,就是heapq,下面代码说明:

一、对列表取top N

>>> import heapq
>>> list1=[2, 3, 3, 4, 7, 9]
>>> nLargestList=heapq.nlargest(3,list1)
>>> print nLargestList
[9, 7, 4]
>>> nSmallestList=heapq.nsmallest(3,list1)
>>> print nSmallestList
[2, 3, 3]
>>> 
nlargest用于取前n大,相反,nsmallest用于取前n小。特此记录

二、对字典取top N

可以用类似列表的方式,把字典的key或value取top N,然后再做相应处理即可。

你可能感兴趣的:(python,top,N,heapq)