在Python中对数组进行哈希处理
可以对列表
进行哈希处理吗?
举个例子,我知道元组
是可以进行哈希的:
>>> hash((1,2,3,4,5,6))
-319527650
但是列表
能不能进行哈希呢?
>>> hash([1,2,3,4,5,6])
hash_value
可能的解决方案:
4 个回答
10
Python不允许你把可变的数据用作字典里的键,因为如果在插入后对这个数据进行了修改,就会导致找不到这个对象。你可以使用元组作为键。
39
如果你真的需要把一个列表当作字典的键,可以先把它转换成字符串。my_list = str(my_list)
79
你可以试试看:
>>> 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'
因为 tuple
(元组)和 frozenset
(冻结集合)是不可变的,所以你可以为它们生成 hash
(哈希值)。而 list
(列表)和 set
(集合)是可变的,所以你不能为它们生成哈希值。