Set (集合)
set 是 Python 中 无序、元素唯一、可变 的数据结构,底层基于 哈希表
-> 插入 / 删除 / 查找 都是 O(1) 时间复杂度。
s = {1, 2, 3} # 字面量
s = set([1, 2, 3]) # 从列表创建
s = set("hello") # {'h', 'e', 'l', 'o'}
s = set() # 空集合,必须这样写
注意:{} 创建的是 dict,而不是 set。
| 特性 | 说明 |
|---|---|
| 无序 | 不保证顺序 |
| 唯一性 | 自动去重 |
| 可变 | 可新增、删除元素 |
| 元素必须可哈希(不可变) | list/dict 不能放入 set |
示例:
{1, 2, 2, 3} # {1, 2, 3}
s.add(4)
| 方法 | 不存在时报错? | 示例 |
|---|---|---|
| remove(x) | ❌ 会报错 | s.remove(3) |
| discard(x) | ✅ 不报错 | s.discard(3) |
| pop() | 随机删除并返回 | s.pop() |
s.clear()
a & b
a.intersection(b)
a | b
a.union(b)
a - b
a.difference(b)
两者不同的元素
a ^ b
a.symmetric_difference(b)
| 操作 | 含义 | 示例 |
|---|---|---|
| issubset() | a ⊆ b | a.issubset(b) |
| issuperset() | a ⊇ b | a.issuperset(b) |
| isdisjoint() | 无交集 | a.isdisjoint(b) |
示例:
{1,2}.issubset({1,2,3}) # True
s = {x * 2 for x in [1, 2, 3]}
# {2, 4, 6}
fs = frozenset({1, 2, 3})
特点:
| 特性 | frozenset |
|---|---|
| 可哈希 | ✅ |
| 可作为 dict key | ✅ |
| 可作为 set 元素 | ✅ |
| 可修改 | ❌ |
uniq = list(set(my_list))
if item in my_set:
...
(set 不保证顺序,但可以这么写)
seen = set()
result = [x for x in items if not (x in seen or seen.add(x))]
if not a.isdisjoint(b):
...
例如:
valid_codes = {"600001", "600002", ...}
if code in valid_codes:
...
new_items = current - old
removed_items = old - current
- 基于哈希表(Hash Table)
- in 判断:O(1)
- 交集/并集:高度优化的 C 实现
❌ set 不支持索引
s = {1, 2, 3}
s[0] # 错误
❌ set 内不能放列表、dict(因为不可哈希)
s = {[1,2,3]} # TypeError
❌ set 无顺序,不适用于保持顺序的场景
| 类型 | 示例 | 说明 |
|---|---|---|
| 创建 | set(), {1,2} | 空集必须用 set() |
| 添加 | add | 添加单个 |
| 删除 | remove / discard | 有区别 |
| 交集 | a & b | 常用 |
| 并集 | `a | b` |
| 差集 | a - b | 找出被删除元素 |
| 对称差 | a ^ b | 找出变化元素 |
| 子集 | issubset | 关系判断 |
| 不可变 | frozenset | 可做 dict key |
| 判断存在 | x in set | O(1) |