Python 从字典返回最大值
我想从字典中返回最大值和它的键,我知道像下面这样的东西应该可以做到这一点Python 从字典返回最大值,python,python-2.7,dictionary,max,Python,Python 2.7,Dictionary,Max,我想从字典中返回最大值和它的键,我知道像下面这样的东西应该可以做到这一点 max(list.iteritems(), key=operator.itemgetter(1)) 但是,如果字典中的最大值为6,并且多个键恰好具有相同的值。。它将始终返回第一个!如何使其将所有具有最大数量的键作为值与值一起返回。这是 具有相同最大值的词典示例: dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2
max(list.iteritems(), key=operator.itemgetter(1))
但是,如果字典中的最大值为6,并且多个键恰好具有相同的值。。它将始终返回第一个!如何使其将所有具有最大数量的键作为值与值一起返回。这是
具有相同最大值的词典示例:
dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}
result = filter(lambda x:x[1] == maximum,dic.items())
>>> maximum_keys(dic)
([3, 4], 2.2984074067880425)
您可以首先使用以下方法确定最大值:
maximum = max(dic.values())
然后根据最大值过滤:
dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}
result = filter(lambda x:x[1] == maximum,dic.items())
>>> maximum_keys(dic)
([3, 4], 2.2984074067880425)
命令行中的示例:
$ python2
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}
>>> maximum=max(dic.values())
>>> maximum
2.2984074067880425
>>> result = filter(lambda x:x[1] == maximum,dic.items())
>>> result
[(3, 2.2984074067880425), (4, 2.2984074067880425)]
如果您想显示键的列表是一个很好的列表和值,您可以定义一个函数:
def maximum_keys(dic):
maximum = max(dic.values())
keys = filter(lambda x:dic[x] == maximum,dic.keys())
return keys,maximum
返回包含键列表和最大值的元组:
dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}
result = filter(lambda x:x[1] == maximum,dic.items())
>>> maximum_keys(dic)
([3, 4], 2.2984074067880425)
使用列表理解的解决方案:
dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}
max_value = max(dic.values()) # maximum value
max_keys = [k for k, v in dic.items() if v == max_value] # getting all keys containing the `maximum`
print(max_value, max_keys)
输出:
2.2984074067880425 [3, 4]
如果这两个值完全相同,并且您没有选择按值查找的选项,那会怎么样?这是一个tie,任何max()算法都需要某种tie分辨率,可能是lamdba函数@艾哈迈德