集合的核心特性
Python 里的集合(set)和数学上的集合概念一致:无序、互异、确定。这意味着:
- 无序:元素没有固定顺序,不能通过索引访问。
- 互异:同一个值只出现一次,自动去重。
- 确定:元素要么在集合里,要么不在,这是
in/not in运算的基础。
集合底层使用哈希表实现,所以成员检查(in)、添加、删除的平均时间复杂度都是 O(1),比列表快得多。但代价是元素必须可哈希(hashable)—— 像 int、str、tuple 这类不可变类型可以,list、dict、甚至 set 本身不行。
创建集合
可以用花括号,但注意 {} 是空字典,不是空集合。要创建空集合,必须用 set()。
set1 = {1, 2, 3, 3, 3, 2}
print(set1) # {1, 2, 3}
set2 = {True, False, True, True, False}
print(set2) # {False, True}
set3 = set('hello')
print(set3) # {'l', 'o', 'e', 'h'}
set4 = set([1, 2, 2, 3, 3, 3, 2, 1])
print(set4) # {1, 2, 3}
set5 = {num for num in range(1, 20) num % == num % == }
(set5)
set6 = {(, ), (, )}
(set6)

