You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<p>作为 dict 的 key 必须是可哈希的,也就是说不能是 list 等可变对象。不信你在 ipython 里运行如下代码:</p>
247
-
<pre><codeclass="py">d = dict()
246
+
<pre><codeclass="language-py">d = dict()
248
247
d[[1]] = 1
249
248
# TypeError: unhashable type: 'list'
250
249
</code></pre>
251
-
252
250
<p>我引用 python 文档里的说法,大家可以自己理解下:</p>
253
251
<pre><code>An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.
254
252
255
253
Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.
256
254
257
255
All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal (except with themselves), and their hash value is derived from their id().
0 commit comments