dict和set的key不可变

来源:互联网 发布:哪个软件可以搜高数题 编辑:程序博客网 时间:2024/05/29 18:28

dict和set的key是不可变的 :

  • tuple虽然是不可变对象,但是只有不含list的tuple才能做key,包含有list的tuple是“可变的”
  • list是可以改变的,所以肯定是不能做key的**
>>> a=(1,2,3)>>> b=(1,[2,3])>>> dict1={a:'A'}>>> dict1[a]'A'>>> dict2={b:'B'}Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: unhashable type: 'list'>>>

这里a是不含list的tuple 作为key不会报错
而b会报错


试试把list放入set,看看是否会报错。

>>> s=set([1,2,3,2])>>> sset([1, 2, 3])>>> list=[3,4]>>> s.add(list)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: unhashable type: 'list'

结论:是一定会报错的 因为set中的key也要求不变 list是可变的

原创粉丝点击