python - 使用 python 替换字典中矩阵键返回错误的选项

标签 python dictionary matrix

我有一个矩阵列表,我想打印该键的值。这是代码:

list1=np.matrix([[ 0.],[ 1.]]),np.matrix([[ 1.],[ 0.]]),np.matrix([[ 1.],[ 0.]])
print (list1)
dictionary = { np.matrix([[ 0.],[ 1.]]): '1' , np.matrix([[ 1.],[ 0.]]):'0'}
output=[dictionary[i] for i in list1]

输出显示如下:

(matrix([[ 0.],
        [ 1.]]), 
 matrix([[ 1.],
        [ 0.]]), 
 matrix([[ 1.],
        [ 0.]]))
dictionary = { np.matrix([[ 0.],[ 1.]]): '1' , np.matrix([[ 1.],[ 0.]]):'0'}
TypeError: unhashable type: 'matrix'

输出结果大概是这样的:

1, 0, 0

由于矩阵不能作为字典的键,有没有办法为矩阵列表赋值?

谢谢。

最佳答案

矩阵不能用作字典的键。如果你想了解更多关于字典键的信息,请查看this site 。即使它有一个__hash__,可变对象也不应该用作哈希,因为如果你改变了值,那么你很可能会得到KeyError

根据this ,numpy矩阵的哈希方法不满足哈希的基本条件之一:

对于所有 i1、i2,如果 hash(i1) != hash(i2),则 i1 != i2

但是,当我尝试使用 hash(np.matrix('1 2; 3 4)) 时,我得到:

>>> from numpy import matrix
>>> hasattr(matrix,'__hash__')
True
>>> hash(matrix('1 2; 3 4'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'matrix'

一种可能的解决方案(可能适用于所有情况,也可能不适用于所有情况):

>>> l = matrix([[0.],[1.]]),matrix([[ 1.],[ 0.]]),matrix([[ 1.],[ 0.]])
>>>dict = {str(matrix([[ 0.],[ 1.]])): '1' ,str(matrix([[ 1.],[ 0.]])):'0'}
>>> output = [dict[str(i)] for i in l]
>>> output
['1', '0', '0']

与矩阵不同,字符串是可散列的

关于python - 使用 python 替换字典中矩阵键返回错误的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51219761/

相关文章:

python - pygame OpenGL 窗口在 Mac OS X 10.6、Python 2.7 上不刷新

python - 使用 Python 打印 PDF 文件

java - 如果所有键都是唯一的, map 的 put 是否需要同步?

c++ - 矩阵类 : "No instance of overloaded function push_back matches the argument list"

c++ - 特征矩阵的下三角

r - 比较两个矩阵之间的行

python - 添加列表直到总和匹配

python - 蓝色混合 : How to upgrade pip?

dictionary - Elixir 按条件过滤映射条目

python - 检查列表中的项目是否存在于字典中