本文介绍了一个python字典中的5个最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本这样的字典:

  A = {'a':10,'b':843, c':39,.....} 

我想获得这5个最大值用这个命令和存储一个新的命令。要得到我做的最大值:

  max(A.iteritems(),key = operator.itemgetter(1))[ 0:] 

也许这是一件容易的事情,但我坚持了很长时间。请帮助!!!

解决方案

你很近您可以使用,并采取前五个要素:

  newA = dict(sorted(A.iteritems(),key = operator.itemgetter(1),reverse = True)[:5])
/ pre>

另请参见:


I have a dictionary like this:

A = {'a':10, 'b':843, 'c': 39,.....}

I want to get the 5 maximum values of this dict and store a new dict with this. To get the maximum value I did:

max(A.iteritems(), key=operator.itemgetter(1))[0:]

Perhaps it is an easy task, but I am stuck on it for a long time. Please help!!!

解决方案

You are close. You can sort the list using sorted and take the first five elements:

newA = dict(sorted(A.iteritems(), key=operator.itemgetter(1), reverse=True)[:5])

See also: Python Sorting HowTo

这篇关于一个python字典中的5个最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 09:59