列表不可散列,但元组可散列? [英] 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:'一个列表',t:'一个元组'}现在,当你执行 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屋!