内置类型 set
的文档说:
class set([iterable])
Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable.
没关系,但为什么这样行得通:
>>> l = range(10)
>>> s = set(l)
>>> s
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
这不是:
>>> s.add([10])
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
s.add([10])
TypeError: unhashable type: 'list'
两者都是列表。初始化过程中是否发生了一些魔法?
最佳答案
当您初始化一个集合时,您提供了一个值列表,这些值必须每个都是可散列的。
s = set()
s.add([10])
与
相同s = set([[10]])
这会引发您现在看到的相同错误。
关于python - 了解 Python 集合的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5022247/