Python 中的散列数组

有可能散列 lists吗?

例如,我知道元组的散列是可能的:

>>> hash((1,2,3,4,5,6))
-319527650

但是有没有可能散列一个 list呢?

>>> hash([1,2,3,4,5,6])
hash_value

可能的解决方案:

Very in depth explanation to the hashing of lists, here.

133325 次浏览

Python doesn't allow you to use mutable data as keys in dictionaries, because changes after insertion would make the object un-findable. You can use tuples as keys.

试试看:

>>> hash((1,2,3))
2528502973977326415
>>> hash([1,2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(frozenset((1,2,3)))
-7699079583225461316
>>> hash(set((1,2,3)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'

所以你可以得到 tuplefrozensethash,因为它们是不可变的,而你不能得到 listsethash,因为它们是可变的。

如果您确实需要使用 list 作为字典键,请尝试首先将其转换为字符串。 < br > my_list = str(my_list)