什么使列表不可容忍? [英] What makes lists unhashable?

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

问题描述

所以列表不可拆卸:

 >>> {[1,2]:3} 
TypeError:不可分类型:'list'

以下页面给出了解释:


列表是一种可变类型,不能用作字典中的键
(它可能会在原位更改,使该键不再位于
/ b> b
$ b

我明白为什么不可以使用可变对象作为字典键。但是,即使我只是尝试对列表进行哈希(与字典创建无关),Python引起了同样的异常。

 >> ;> hash([1,2])
TypeError:unhashable类型:'list'

Python这样做是为了保证不可变类型永远不会被用作字典键?或者是否有另一个原因使得可变对象不可能哈希,不管我打算如何使用它们?

解决方案

字典和集使用哈希算法来唯一地确定一个项目。这些算法使用用作键的项来提取唯一的哈希值。由于列表是可变的,所以列表的内容可以改变。在将列表作为关键字列入字典后,如果列表的内容发生变化,则哈希值也将更改。如果哈希值在存储在字典中的特定时隙之后发生更改,则会导致字典不一致。例如,最初列表将被存储在基于哈希值确定的位置A处。如果哈希值发生变化,并且如果我们查找列表,我们可能找不到位置 A ,或者根据新的哈希值,我们可能会找到一些其他对象。



由于不可能得出一个哈希值,内部有没有为列表定义哈希函数

  PyObject_HashNotImplemented,/ * tp_hash * / 

由于散列函数没有实现,当您将其用作字典中的键,或强制尝试使用 hash 函数获取哈希值时,它无法对其进行哈希,因此无法使用不可靠类型

  TypeError:不可分类型:'list'


So lists are unhashable:

>>> { [1,2]:3 }
TypeError: unhashable type: 'list'

The following page gives an explanation:

A list is a mutable type, and cannot be used as a key in a dictionary (it could change in-place making the key no longer locatable in the internal hash table of the dictionary).

I understand why it is undesirable to use mutable objects as dictionary keys. However, Python raises the same exception even when I am simply trying to hash a list (independently of dictionary creation)

>>> hash( [1,2] )
TypeError: unhashable type: 'list'

Does Python do this as a guarantee that mutable types will never be used as dictionary keys? Or is there another reason that makes mutable objects impossible to hash, regardless of how I plan to use them?

解决方案

Dictionaries and sets use hashing algorithms to uniquely determine an item. And those algorithms make use of the items used as keys to come up the unique hash value. Since lists are mutable, the contents of a list can change. After allowing a list to be in a dictionary as a key, if the contents of the list changes, the hash value will also change. If the hash value changes after it gets stored at a particular slot in the dictionary, it will lead to an inconsistent dictionary. For example, initially the list would have gotten stored at location A, which was determined based on the hash value. If the hash value changes, and if we look for the list we might not find it at location A, or as per the new hash value, we might find some other object.

Since, it is not possible to come up with a hash value, internally there is no hashing function defined for lists.

PyObject_HashNotImplemented,                /* tp_hash */

As the hashing function is not implemented, when you use it as a key in the dictionary, or forcefully try to get the hash value with hash function, it fails to hash it and so it fails with unhashable type

TypeError: unhashable type: 'list'

这篇关于什么使列表不可容忍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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