矩阵作为字典键

jul*_*ria 6 python dictionary numpy

我刚刚开始使用numpy它的matrix模块(非常非常有用!),我想使用矩阵对象作为字典的键,所以我检查了是否实现matrix__hash__方法:

>>> from numpy import matrix
>>> hasattr(matrix, '__hash__')
True
Run Code Online (Sandbox Code Playgroud)

它确实如此!很好,所以这意味着它可以是字典的关键:

>>> 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'}
Run Code Online (Sandbox Code Playgroud)

成功了!现在,让我们继续测试:

>>> 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]])
Run Code Online (Sandbox Code Playgroud)

什么?因此,它适用于相同的矩阵,但它不适用于具有完全相同内容的另一个矩阵?让我们看看__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
Run Code Online (Sandbox Code Playgroud)

因此,from 的__hash__方法返回相同的不同值.matrixnumpymatrix

这是正确的吗?那么,这是否意味着它不能用作字典键?如果它不能使用,它为什么__hash__实施?

JBe*_*rdo 9

将可变对象用作字典的键是错误的,因为它的哈希值应在您更改数据后立即更改,但插入时使用的值将保留.

在我的测试中,Python 3.2.2中的numpy引发了一个TypeError:

TypeError: unhashable type: 'matrix'
Run Code Online (Sandbox Code Playgroud)

但是在Python 2.7上它仍然允许散列,但是当你更改数据时哈希值永远不会改变,所以它作为字典键是无用的,因为matrix添加到具有相同散列的字典中的许多对象会降低散列表,因此插入将O(n^2)代替O(1).

也许他们没有删除哈希值以避免在Python 2.x上破坏某些API,但不依赖它!