标签:python
最近在程序中需要取一个列表的top 3元素,就是去一个列表中数值最大的3个元素。这可以用Python的heapq模块来处理。
import heapq myList = [5, 2, 6, 12, 7, 3, 4, 9] topNum = 3 nlargestList = heapq.nlargest(topNum, myList) #取最大3个元素 nsmallestList = heapq.nsmallest(topNum, myList) #取最小3个元素 print nlargestList #输出结果 print nsmallestList
import heapq
myDict = {1:'a', 3:'d', 8:'g', 5:'m', 9:'t', 4:'s', 2:'u'} #定义一个字典
topNum = 3
nlargestList = heapq.nlargest(topNum, myDict.keys()) #取key值最大的3个元素
nsmallestList = heapq.nsmallest(topNum, myDict.keys()) #取key值最小的3个元素
for key in nlargestList: #输出结果
print key,myDict[key]
for key in nsmallestList:
print key,myDict[key]
import heapq
myDict = {1:'a', 3:'d', 8:'g', 5:'m', 9:'t', 4:'s', 2:'u'}
topNum = 3
nlargestList = heapq.nlargest(topNum, myDict.values()) #取value值最大的3个元素,注意与上一程序区别
nsmallestList = heapq.nsmallest(topNum, myDict.values()) #取value值最小的3个元素,注意与上一程序区别
for value in nlargestList: #输出结果
for key in myDict:
if myDict[key] == value:
print key,myDict[key]
for value in nsmallestList: #输出结果
for key in myDict:
if myDict[key] == value:
print key,myDict[key]我是在Linux环境下,输入:python test.py,就可以运行程序了。
【Python】Python取top N相关的模块:heapq模块,布布扣,bubuko.com
【Python】Python取top N相关的模块:heapq模块
标签:python
原文地址:http://blog.csdn.net/xiaoguaihai/article/details/26392263