Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果嵌套字典包含NaN值,是否在其中输入?_Python_Dictionary - Fatal编程技术网

Python 如果嵌套字典包含NaN值,是否在其中输入?

Python 如果嵌套字典包含NaN值,是否在其中输入?,python,dictionary,Python,Dictionary,我在python中有以下数据 my_dictionary = { 'key1': {'a': 1, 'b': 1, 'c': 10}, 'key2': {'a': 1, 'b': 1, 'c': 'NaN'}, 'key3': {'a': 1, 'b': 1, 'c': 12} ... ... } 我的兴趣是找到最大值为C的键。 到目前为止,下面的代码运行良好,但如果“c”具有NaN值(如我的示例中所示),它不会给出正确的结果

我在python中有以下数据

my_dictionary = {
      'key1': {'a': 1, 'b': 1, 'c': 10}, 
      'key2': {'a': 1, 'b': 1, 'c': 'NaN'}, 
      'key3': {'a': 1, 'b': 1, 'c': 12}
       ...
       ...
}
我的兴趣是找到最大值为C的键。 到目前为止,下面的代码运行良好,但如果“c”具有NaN值(如我的示例中所示),它不会给出正确的结果? 我编写了以下代码

max(my_dictionary, key=lambda v: my_dictionary[v]['c'])

我需要在上述代码中进行哪些更改才能在C中解释NaN值?

您可以为NaN提供默认值:

print(max(my_dictionary, key=lambda v: my_dictionary[v]['c'] 
     if isinstance(my_dictionary[v]['c'],int) else float("-inf")))
您还可以使用函数作为键传递,而不是两次查找值,并使用
Number
处理不只是int的情况:

from numbers import Number
def key(x):
    val = my_dictionary[x]['c']
    return  val if isinstance(val, Number) else float("-inf")
print(max(my_dictionary, key=key))

您希望它如何处理
NaN
s?您的
'NaN'
是一个字符串。如果您真的想要NaN,请使用
float('NaN')
我只是写了一些类似的东西,但我想使用-sys.maxint/maxsize。你的版本更好,-inf将比任何东西都小。另外,使用查找NaN。你有我的剑。任何我的弓。还有我的投票。@khan,只要
mx=max(my_dictionary,key=key))
,第一个代码也是一样的
mx=max(my_dictionary,key=lambda v:my_dictionary[v]['c'],if isinstance(my_dictionary[v]['c'],int)else float(“-inf”)