Python字典中的最小值

Aas*_*war 4 python sorting dictionary min

我有 python Dict,当我使用min(). 看我的代码

scores = {leaf_size: round(get_mae(leaf_size, train_X, val_X, train_y, val_y)) for leaf_size in candidate_max_leaf_nodes}
best_tree_size = min(scores, key=scores.get)
Run Code Online (Sandbox Code Playgroud)

get_mae() 只是一个计算平均绝对误差的函数。

但它显示以下错误

TypeError                                 Traceback (most recent call last)
<ipython-input-48-aa5b1fc6e492> in <module>
      8 # print(dict)
      9 scores = {leaf_size: round(get_mae(leaf_size, train_X, val_X, train_y, val_y)) for leaf_size in candidate_max_leaf_nodes}
---> 10 best_tree_size = min(scores, key=scores.get)
     11 # list = scores.items()
     TypeError: 'int' object is not callable
Run Code Online (Sandbox Code Playgroud)

Ray*_*ger 7

您可能已将min用作变量并隐藏了内置函数。

尝试这个:

best_tree_size = __builtins__.min(scores, key=scores.get)
Run Code Online (Sandbox Code Playgroud)

这将使用实际的min()函数而不是引用int值的min变量。