Oph*_*lia 7 python dictionary max python-2.7
我想从字典中返回最大值及其键,我知道下面的内容应该可以解决问题
max(list.iteritems(), key=operator.itemgetter(1))
Run Code Online (Sandbox Code Playgroud)
但是,如果字典中的最大值为6,并且多个键具有相同的值,则它将始终返回第一个值!如何让它返回所有具有最大数字的键以及值.以下是具有相同最大值的字典示例:
dic={0: 1.4984074067880424, 1: 1.0984074067880423, 2: 1.8984074067880425, 3: 2.2984074067880425, 4: 2.2984074067880425}
Run Code Online (Sandbox Code Playgroud)
Rom*_*est 19
使用列表理解的解决方案:
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)
Run Code Online (Sandbox Code Playgroud)
输出:
2.2984074067880425 [3, 4]
Run Code Online (Sandbox Code Playgroud)
您可以首先确定最大值:
maximum = max(dic.values())
Run Code Online (Sandbox Code Playgroud)
然后filter基于最大值:
result = filter(lambda x:x[1] == maximum,dic.items())
Run Code Online (Sandbox Code Playgroud)
命令行中的示例:
$ 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)]
Run Code Online (Sandbox Code Playgroud)
鉴于您想显示键列表是一个不错的列表和值,您可以定义一个函数:
def maximum_keys(dic):
maximum = max(dic.values())
keys = filter(lambda x:dic[x] == maximum,dic.keys())
return keys,maximum
Run Code Online (Sandbox Code Playgroud)
它返回一个包含键列表和最大值的元组:
>>> maximum_keys(dic)
([3, 4], 2.2984074067880425)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46307 次 |
| 最近记录: |