在使用list创建set的时候,一直出现TypeError: unhashable type: 'list',这种错误,检查代码,并没有出错,只可能是有些未知的错误,之前可能没有遇到过,百度后发现,原来是hash错误,就是list中的值不能hash。但是,set的创建也需要使用list,只能够在声明的时候直接使用list创建可以。
>>> s = set(range(1, 10))
>>> s
set([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> li = range(1, 11)
>>> li.append(range(1, 11))
>>> print li
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
>>> s = set(li)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
同样的,使用list和dict去创建dict的时候,同样会出现这种错误
>>> d={[] : "str", {}: "11"}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Python不支持dict的key为list或dict类型,因为list和dict类型是unhashable(不可哈希)的。