gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:16:23 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com