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

                       
 

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
  • 2
  • 3
  • (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
   
   
  • 1
  • 2
  • 3
  • 4
  • 5

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
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/hftytf/article/details/87872412