python - 了解 Python 集合的行为

标签 python set

内置类型 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/

相关文章:

python - 我试图阻止列表循环,因为它是空的。我一直得到的只是索引错误无法从空列表中弹出

python - 如何更新播放列表中的所有 Youtube 视频描述?

c++ - 奇怪的编译错误 : ISO C++ forbids declaration of ‘set’ with no type

c++ - std::lower_bound 与 std::set 的时间复杂度是多少?

python - 通过内部设置的列去除重复的行

Powershell,内置的集合交叉点?

python - 如果表中不存在则从列表中插入记录

python - 记忆化python函数

python - 无法向由python的xlsxwriter模块创建的柱形图添加数据标签

c++ - 使用 STL 容器设置 upper_bound