列表不可散列,但元组可散列? [英] List unhashable, but tuple hashable?

查看:40
本文介绍了列表不可散列,但元组可散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何散列列表?我被告知应该先转换为元组,例如[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆