【问题标题】:figure out the which parameter produces data type error in python for a given function?找出哪个参数在 python 中为给定函数产生数据类型错误?
【发布时间】:2017-04-10 11:30:19
【问题描述】:

我只是在玩 Ipython,我收到以下错误:

In [108]: feed_dict_test = {x:x, y_true:y_true, y_true_cls:data.test.cls}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-108-2fdafc34bea7> in <module>()
----> 1 feed_dict_test = {x:x, y_true:y_true, y_true_cls:data.test.cls}

TypeError: unhashable type: 'numpy.ndarray'

问题:

该错误清楚地说明了“TypeError”,但我如何确定三个参数中的哪个参数会产生此错误?在这种情况下 x?y_true?y_true_cls?

【问题讨论】:

  • 键应该是不可变类型。
  • 这些关键对象中的哪个是numpy.ndarray 的实例,或者如果有多个,则声明第一个。顺便说一句,您正在创建字典,而不是调用函数,尽管您可能想将字典作为关键字参数传递?如果是这样,您需要使用字符串作为键:{'x':x, 'y_true': y_true.....}
  • 谢谢回复,有3个参数,哪个参数会导致错误?,有什么办法可以通过调试弄清楚?
  • @Whoami:我认为您无法从调试消息中看出。您可以打印出对象类型以查找违规对象,也可以使用isinstance(obj, collections.Hashable)
  • 谢谢@mhawke

标签: python python-2.7 ipython


【解决方案1】:

您的字典中的一个键是'numpy.ndarray' 类型。 字典的定义如下:{key:value},因此在本例中,键为:xy_truey_true_cls

在字典中,所有的键都需要是可散列的。 'numpy.ndarray' 不可散列,因此您不能将其用作字典中的键。

要找出python中对象的类型,您可以使用函数type()

>>> a = np.zeros((10,10))
>>> type(a)
numpy.ndarray

在您定义的字典中,您使用对象x 作为键来查找对象x。这可能是多余的。您的意思是写:{'x':x, 'y_true':y_true, 'y_true_cls':data.test.cls}

【讨论】:

  • 另一种定义字典的方法是dict(x=x, y_true=y_true)。这里不必引用键名。这可能是一种方便,但我怀疑在这种情况下它可能是混乱的根源。 OP当然不是要使用数组本身作为键将数组保存到字典中。
猜你喜欢
  • 1970-01-01
  • 2017-03-29
  • 2016-03-25
  • 2017-03-07
  • 2018-08-06
  • 1970-01-01
  • 2022-06-19
  • 1970-01-01
  • 2020-09-10
相关资源
最近更新 更多