为什么字典元素不能与 python 中的 max 函数一起使用?

Why the dictionary element is not working with the max function in python?

在使用训练器模块时,我使用字典来存储观察到的参数以及参数值对应的数据准确度。参数是字典的键,准确度是值。

我在这里使用了sklearn.metrics工具来计算准确度。但结果显示以下行为。

def fit(self, X, Y):
    acc={}
    best_b = 0
    for b in range(0, X.shape[1] + 1):
      self.b=b
      Y_Pred = self.predict(X)
      acc[b]=accuracy_score(Y_Pred,Y)
    print(type(acc))
    best_b = max(acc, key=acc.get)
    self.b = best_b
    print("Best b : ", self.b, " with highest accuracy : ", acc[self.b])

输出:

<class 'dict'>
<ipython-input-184-8b55ae4bcee2> in fit(self, X, Y)
     21       acc[b]=accuracy_score(Y_Pred,Y)
     22     print(type(acc))
---> 23     best_b = max(acc, key=acc.get)
     24     self.b = best_b
     25     print("Best b : ", self.b, " with highest accuracy : ", acc[self.b])

TypeError: 'list' object is not callable

为什么字典被视为列表对象?

字典中 max 的这种用法是有效的:

In [1]: acc = {}
In [2]: acc = {'a':1, 'b':3, 'c':2}
In [3]: max(acc, key=acc.get)
Out[3]: 'b'
In [4]: type(max)
Out[4]: builtin_function_or_method

错误提示您重新定义了max。它不再是内置函数,而是一个列表。这就是为什么我一直在问 type(max).

In [5]: max=[1,2,3]
In [6]: max(acc, key=acc.get)
Traceback (most recent call last):
  File "<ipython-input-6-d5bdb2afa5ad>", line 1, in <module>
    max(acc, key=acc.get)
TypeError: 'list' object is not callable

In [7]: type(max)
Out[7]: list