【问题标题】:Why the dictionary element is not working with the max function in python?为什么字典元素不能与 python 中的 max 函数一起使用?
【发布时间】:2020-10-25 07:12:56
【问题描述】:

在使用培训模块时,我使用字典来存储正在观察的参数以及参数值数据的相应准确性。参数是字典的键,准确度是值。

我在这里使用了 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

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

【问题讨论】:

  • type(max) 是什么?
  • type(acc) 是检查 acc 变量的数据类型。而这里的max应该返回一个int64值,key对应最大精度值。
  • 我问的不是这个!
  • 我认为这会有所帮助:stackoverflow.com/questions/268272/…

标签: python-3.x list numpy dictionary max


【解决方案1】:

在字典中使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 2020-10-12
    • 2011-11-15
    相关资源
    最近更新 更多