Python 2.x vs Python 3.x(四)—— TypeError: unhashable type
2016-04-01 08:54
561 查看
list 是可变类型,无法进行 hash,或者说凡可变类型都无法进行 hash;
(1)range 在 Python 2.x 得到一个 list 类型,自然不可哈希
(2)range 在 Python 3.x 得到的是 range 类型,可哈希,
(3)Python 2.x 中的 xrange 的用法等价于 Python 3.x 中的 range,仅用于迭代(或者进行强转为其他容器)
所以在 Python 2.x,不可使用 range 作为 dict 的 key 类型,而必须使用 xrange。
list 类型不可 hash,出现在 set(a),使用 tuple 替换:
1. list 作为字典(dict)的 key
注意字典,无论是 Python 2.x 还是 Python 3.x 都要求它的 key 类型是可哈希的(hashable),>>> d = {} >>> d[[1, 2]] = 'good' TypeError: unhashable type: 'list'
(1)range 在 Python 2.x 得到一个 list 类型,自然不可哈希
(2)range 在 Python 3.x 得到的是 range 类型,可哈希,
(3)Python 2.x 中的 xrange 的用法等价于 Python 3.x 中的 range,仅用于迭代(或者进行强转为其他容器)
所以在 Python 2.x,不可使用 range 作为 dict 的 key 类型,而必须使用 xrange。
2. nested list
a = [[1, 2], [3, 4], [5, 6]] try: print(list(set(a))) except TypeError, e: print 'Error:', e
list 类型不可 hash,出现在 set(a),使用 tuple 替换:
a = [[1, 2], [3, 4], [5, 6]] try: print(list(set(tuple(i) for i in a))) except TypeError, e: print 'Error:', e
相关文章推荐
- python3.5 + django1.9.1+mysql
- python中的条件语句,分支语句以及逻辑运算符和比较运算符
- 学python过程中遇到的一些问题及解决方法
- python爬虫(爬游民星空图片)_beautifulsoup爬虫模版
- python基于隐马尔可夫模型实现中文拼音输入
- python初识
- Python学习第十五天
- python 下载页面数据 到 execl表
- 一行 Python 实现并行化 -- 日常多线程操作的新思路
- Python学习笔记day11
- python 多继承(新式类) 三
- Python基础知识注意点
- Python写爬虫-爬甘农大学校新闻
- python STMP
- Python 2.7 学习笔记 面向对象的编程
- Python CSV Reader/Writer 例子
- 每天一篇python:时间日期篇
- python之邮件操作
- python语言学习1——初识python
- Python 标准库—— datetime(运行时间的判断)