列表不可用,但元组可哈希? [英] List unhashable, but tuple hashable?
问题描述
在如何散列列表?我被告知应该先转换为元组,例如 [1,2,3,4,5]
至(1,2,3,4,5)
。
所以第一个不能被哈希,但第二个可以。为什么 * ?
* 我不是在寻找详细的技术说明,而是为了直觉
主要是因为元组是不可变的。假设以下工作:
>>> l = [1,2,3]
>>> t =(1,2,3)
>>> x = {l:'a list',t:'tuple'}
现在会发生什么当你做 l.append(4)
?您已修改字典中的密钥!远道而来!如果你熟悉哈希算法的工作原理,这应该会吓到你。另一方面,元组是绝对不变的。 t + =(1,)
可能看起来像是在修改元组,但实际上并不是:它只是创建一个新的元组,密钥不变。
In How to hash lists? I was told that I should convert to a tuple first, e.g. [1,2,3,4,5]
to (1,2,3,4,5)
.
So the first cannot be hashed, but the second can. Why*?
*I am not really looking for a detailed technical explanation, but rather for an intuition
Mainly, because tuples are immutable. Assume the following works:
>>> l = [1, 2, 3]
>>> t = (1, 2, 3)
>>> x = {l: 'a list', t: 'a tuple'}
Now, what happens when you do l.append(4)
? You've modified the key in your dictionary! From afar! If you're familiar with how hashing algorithms work, this should frighten you. Tuples, on the other hand, are absolutely immutable. t += (1,)
might look like it's modifying the tuple, but really it's not: it simply creating a new tuple, leaving your dictionary key unchanged.
这篇关于列表不可用,但元组可哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!