python的TypeError: unhashable type(list/set/dict)问题
来源:互联网 发布:爱普生mp288清零软件 编辑:程序博客网 时间:2024/05/17 06:34
今天在使用python处理一个列表时,遇到这样一个问题,列表里面的元素都是列表,我想把它去重,于是使用set处理一下,但是出现了这个error。
后来查了一下,原因是因为list是不能哈希的。
这一异常通常出现在,调用 set(…) 来构造一个 set (集合类型)时,set() 需要传递进来可哈希的元素(hashable items)。
(1)list、set、dict:是不可哈希的
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
(2)int、float、str、tuple:是可以哈希的
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
(3)list 不使用 hash 值进行索引,故其对所存储元素没有可哈希的要求;set / dict 使用 hash 值进行索引,也即其要求欲存储的元素有可哈希的要求。
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
(4)dict 仅对键(key)有可哈希的要求,对值(value)无此要求。
- 1
- 2
- 1
- 2
注:可能你会问,set 不是可以接受 list,并将其转换为 set 吗?比如set([1, 2, 3])
,注意,上文说的可哈希,不可哈希,是对可迭代类型(iterables)所存储元素(elements)的要求,[1, 2, 3]
是可迭代类型,其存储元素的类型为int
,是可哈希的,如果set([[1, 2], [3, 4]])
,[[1, 2], [3, 4]]
list of lists(list 构成的 list)自然是可迭代的,但其元素为 [1, 2]
和 [3, 4]
是不可哈希的。
为什么 list 是不可哈希的,而 tuple 是可哈希的
(1)因为 list 是可变的在它的生命期内,你可以在任意时间改变其内的元素值。
(2)所谓元素可不可哈希,意味着是否使用 hash 进行索引
(3)list 不使用 hash 进行元素的索引,自然它对存储的元素有可哈希的要求;而 set 使用 hash 值进行索引。
- python的TypeError: unhashable type(list/set/dict)问题
- Python debug——TypeError: unhashable type(list/set/dict)
- TypeError: unhashable type: 'dict'
- TypeError: unhashable type: 'list'
- TypeError: unhashable type: 'list'
- TypeError: unhashable type: 'matrix'解决方法 以及 Python3下map函数的显示问题、 python numpy中nonzero()的用法
- Python 2.x vs Python 3.x(四)—— TypeError: unhashable type
- TypeError: unhashable type: 'matrix'解决方法
- TypeError: unhashable type: 'matrix'解决方法
- Python - list, tuple, dict, set的区别
- Python的list、tuple、dict、set
- python的dict、list、set学习运用
- python(list,tuple,dict,set)
- 机器学习实战:TypeError: unhashable type: 'matrix'
- python list tuple dict set
- Python list,Dict和Set
- Python--list,tuple,dict,set.
- 6.python的set、list和dict的解析
- java.lang.reflect.UndeclaredThrowableException
- ffmpeg编码个参数的设置以及作用
- recursiveDescription - 打印UIView对象
- Qt "hello Qt!"显示
- 深入理解onSaveInstanceState和onRestoreInstanceState
- python的TypeError: unhashable type(list/set/dict)问题
- 特征工程整体框架图
- Ionic2跨平台项目(七)浏览器中使用Native包和插件
- 软编码Flv 到Mp4 容器(十二) fmp4 mdat box详解
- 判断回文数字
- 虚拟机NAT模式网络连接设置ssh
- 最近一个低级错误犯了两次
- 利用jdk1.8的新特性实现模板方法模式
- Spring MVC入门 —— 学SpringMVC