Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.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 Can';t将dict.values()与min func';s键_Python_Dictionary_Min - Fatal编程技术网

Python Can';t将dict.values()与min func';s键

Python Can';t将dict.values()与min func';s键,python,dictionary,min,Python,Dictionary,Min,我创建了一个dict: scores = {5: 35044.51299744237, 25: 29016.41319191076, 50: 27405.930473214907, 100: 27282.50803885739, 250: 27893.822225701646, 500: 29454.18598068598} 我可以使用min函数,它使用: min(scores.keys(),key = lambda x: scores[x]) min(scores, key=scores.

我创建了一个dict:

scores = {5: 35044.51299744237, 25: 29016.41319191076, 50: 27405.930473214907, 100: 27282.50803885739, 250: 27893.822225701646, 500: 29454.18598068598} 
我可以使用min函数,它使用:

min(scores.keys(),key = lambda x: scores[x])
min(scores, key=scores.get)
但当我尝试使用:

min(scores.keys(),key = scores.values())
我得到一个错误:

“dict_values”对象不可调用


有人能解释一下原因吗?

键必须是一个可以用一个参数调用的函数
values()
不是一个函数,它是一个视图,是目录中所有值的序列。虽然
得分,但values
是一个函数,不能用参数调用


还不清楚您认为您的代码片段即使有效,实际会起到什么作用。在一组值中查找键会做什么呢?

您得到的
'dict\u values'对象是不可调用的
,因为
min
中的
参数需要一个可调用的对象(一个具有
调用方法的对象)。在您的例子中,
scores.values()
返回类型为
的对象,该对象不可调用

>>> dct = {}
>>> type(dct.values())
<class 'dict_values'>
>>> callable(dct.values())
False
或使用
运算符。itemgetter

from operator import itemgetter
min(scores.items(), key=itemgetter(1))[0]
换句话说,
min
key
函数应用于
scores.items()
提供的元素

如果您尝试
scores.keys()
,如您的问题所示,
min
函数对其值一无所知。尽管您仍然可以这样做:

min(scores.keys(), key=lambda key: scores[key])

但我不推荐这种解决方案,因为
key
函数包含
scores
,在某些情况下会导致未定义的行为。

为什么它会起作用?key是一个应用于迭代器的每个元素以确定要比较的实际值的函数。当您传递key=scores.values()时,您会得到DictValues对象(类似于list),它不是一个函数
key
应该是一个传递iterable的每个项的函数。函数应该返回一个值,通过该值可以找到
min
。因为您直接调用
scores.values()
,它返回一个
dict\u values
对象作为
min
的键函数。Min尝试将此
dict_值作为函数调用。由于其无函数(不可调用),因此会引发上述错误。
min(scores.keys(), key=lambda key: scores[key])