【发布时间】:2012-02-07 10:51:00
【问题描述】:
我刚刚开始使用numpy 及其matrix 模块(非常非常有用!),我想使用矩阵对象作为字典的键,所以我检查了matrix 是否有@ 987654324@方法实现:
>>> from numpy import matrix
>>> hasattr(matrix, '__hash__')
True
确实如此!很好,所以这意味着它可以是字典的键:
>>> m1 = matrix('1 2 3; 4 5 6; 7 8 9')
>>> m1
matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> m2 = matrix('1 0 0; 0 1 0; 0 0 1')
>>> m2
matrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> matrix_dict = {m1: 'first', m2: 'second'}
工作!现在,让我们继续测试:
>>> matrix_dict[m1]
'first'
>>> matrix_dict[matrix('1 2 3; 4 5 6; 7 8 9')]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
什么?那么,它适用于同一个矩阵,但它不适用于另一个具有完全相同内容的矩阵?让我们看看__hash__ 会返回什么:
>>> hash(m1)
2777620
>>> same_as_m = matrix('1 2 3; 4 5 6; 7 8 9')
>>> hash(same_as_m)
-9223372036851998151
>>> hash(matrix('1 2 3; 4 5 6; 7 8 9')) # same as m too
2777665
因此,来自numpy 的matrix 的__hash__ 方法为相同的matrix 返回不同的值。
这是对的吗?那么,这是否意味着它不能用作字典键呢?而如果不能使用,为什么还要实现__hash__?
【问题讨论】:
-
Python 对象默认是可散列的——你必须为不可散列的类禁用它。可能只是
numpy的遗漏。 -
矩阵是下面的 ndarray,默认情况下它们也是可散列的 - 我假设你在使用它们时也会遇到同样的问题。
-
@jozzas,我很惊讶可以使用矩阵作为字典键,因为我知道 ndarrays 不能用作键并且矩阵是 ndarray 的子类
标签: python dictionary numpy