Python Can';t将dict.values()与min func';s键
我创建了一个dict: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.
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])