您的位置:首页 > 编程语言 > Python开发

Python 2.x vs Python 3.x(四)—— TypeError: unhashable type

2016-04-01 08:54 561 查看
list 是可变类型,无法进行 hash,或者说凡可变类型都无法进行 hash;

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: