简体   繁体   English

无法散列的类型错误

[英]Unhashable type error

Trying to do this: 尝试这样做:

ls = np.empty
ls =getColA()
rs = np.empty
rs=getColG()
x = dict(itertools.izip(ls,rs))

and getting this error: 并得到此错误:

TypeError: unhashable type: 'numpy.ndarray'

would appreciate if anyone could help me out. 如果有人可以帮助我,我将不胜感激。

When you are using itertools.izip(ls,rs) the first column will be contain numpy arrays which are not hashable to stand as dictionary keys. 当您使用itertools.izip(ls,rs) ,第一列将包含numpy数组,这些数组不可散列为字典键。

You have to convert them to a hashable iterable like tuple instead. 您必须将它们转换为类似tuple可哈希迭代。 Also if you want to concatenate two numpy arrays along their second axis it's better to use np.column_stack() instead of itertools.izip() . 另外,如果要沿第二个轴连接两个numpy数组,最好使用np.column_stack()而不是itertools.izip()

Also It's not clear that what the getColA object is and what it's returning. 还不清楚getColA对象是什么以及它返回什么。 Maybe you can modify that callable object in order to make a more proper result. 也许您可以修改该可调用对象以得到更适当的结果。

A dict must have the key set as a hashable type. dict必须将键设置为可哈希类型。

You are trying to create a type using a non-hashable type (numpy.ndarray). 您正在尝试使用非哈希类型(numpy.ndarray)创建类型。

This is why you get this error. 这就是为什么您会收到此错误的原因。

In you case, you could do: 在这种情况下,您可以执行以下操作:

x = dict(itertools.izip(tuple(ls),rs))

There several things that don't make sense 有几件事没有道理

ls = np.empty
ls =getColA()

np.empty is a function. np.empty是一个函数。 You assign that to ls ; 您将其分配给ls then you assign the result of getColA() to ls . 然后将getColA()的结果分配给ls That wipes out the first assignment. 这样就消除了第一个任务。 Do you think the first assignment defines the ls variable as an array? 您是否认为第一个赋值将ls变量定义为数组? That's not how Python works. 那不是Python的工作方式。 Variables don't have a type. 变量没有类型。

x = dict(itertools.izip(ls,rs))

You didn't tell us what getColA() returns, but the error indicates that it is an array. 您没有告诉我们getColA()返回什么,但是错误表明它是一个数组。 1d? 1天? 2d? 2d?

This sort of dictionary building works with 1d arrays (I'm using PY3) 这种字典的构建适用于一维数组(我正在使用PY3)

In [497]: dict(itertools.zip_longest(np.arange(3),np.arange(10,13)))
Out[497]: {0: 10, 1: 11, 2: 12}

but not with 2d 但不是2d

In [498]: dict(itertools.zip_longest(np.arange(6).reshape(2,3),np.ones((2,3))))
...
TypeError: unhashable type: 'numpy.ndarray'

That's because the zip on 2d returns the rows of the arrays, and the rows themselves are arrays: 这是因为2d上的zip返回数组的行,而行本身就是数组:

In [499]: list(itertools.zip_longest(np.arange(6).reshape(2,3),np.ones((2,3))
     ...: ))
Out[499]: 
[(array([0, 1, 2]), array([ 1.,  1.,  1.])),
 (array([3, 4, 5]), array([ 1.,  1.,  1.]))]

Why do you want to use an array as dictionary key? 为什么要使用数组作为字典键?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM