python - 如何从字典中获取第二大值的第一个键?
问题描述
我想从给定的第二大值中获取第一个键。使用这个程序,我可以获得给定值最大的第一个键,但我不知道如何告诉它我想要第二个。另一方面,我必须能够使用 None 值并且它没有通过它们,我能做什么?
def f(x):
"""Return the first ascending KEY ordering of a dictionary
based on the second biggest value that is given in a dictionary
biggest value that is given in a dictionary"""
dict_face = x
d = max(dict_face, key=dict_face.get)
print(d)
####
asserts
####
f({'a': 1, 'b': 2, 'c': 2, 'd': 500}) == 'b'
f({'a': 0, 'b': 0, 'c': 2, 'd': 500}) == 'c'
f({'a': None, 'b': None, 'c': None, 'd': 500}) == None
###
output:
d
d
File "/Users/[...]/dict_biggest_value.py", line 7, in f
d = max(dict_face, key=dict_face.get)
TypeError: '>' not supported between instances of 'NoneType' and 'NoneType'
谢谢!
解决方案
我不认为'max'会给你你想要的功能。此外,我认为您必须考虑如果您只有 1 或 0 值会发生什么。你也可以想想你想怎么处理None
。我个人将其用作“负无穷大”,即可能的最小值。
我认为你可以写这样的东西:
def second_to_max(input):
# in here, you track both the max value and the next largest value
max = None
s_max = None
retVal = ''
for key, val in input.items():
# check if val is greater than max,
# if so assign max to s_max and val to max
# and key to retVal
# You'd have special cases for if max and s_max are None,
# since you can't actually compare None to an integer
return retVal
推荐阅读
- python - PyCharm 找不到 sqlite3 模块
- java - UPDATE AND REPLACE 部分或带参数的字符串/记录
- go - 自动将用户添加到 Cognito 组?
- reactjs - 在反应应用程序中分离两个不同的用户界面
- javascript - 无法在 React Native 中对齐文本
- image - 电子纸显示器在arduino上显示乱码而不是图片
- git - 将代码从 dev 合并并推送到 master 的步骤
- batch-file - 从导出的注册表信息排列结果格式时出现问题
- java - 如何在 log4j/tomcat 环境中禁用 gc 日志?
- javascript - HERE 地图使用鼠标单击绘制多边形