Python3 集合
Unordered unique elements, O(1) membership, set algebra, and frozenset.
Key Points`set` gives O(1) membership and automatic dedupe; use it whenever you would otherwise scan a list with `in`.
Basics
Python
tags = {"python", "backend", "python"} # {'python', 'backend'},自动去重
empty = set() # 注意:{} 是空字典,不是空集合
tags.add("api")
tags.discard("backend") # 不存在也不报错(remove 会抛 KeyError)
print("api" in tags) # O(1)
print(len(tags))Dedupe While Keeping Order
A set does not preserve order. To dedupe a list while keeping the first occurrence order, use dict.fromkeys.
Python
items = ["b", "a", "b", "c", "a"]
print(list(set(items))) # 顺序不可预测
print(list(dict.fromkeys(items))) # ['b', 'a', 'c'] 保序去重Set Algebra
| Operation | Operator | Method | Result |
|---|---|---|---|
| Union | a | b | a.union(b) | In a or b |
| Intersection | a & b | a.intersection(b) | In both |
| Difference | a - b | a.difference(b) | In a, not b |
| Symmetric diff | a ^ b | a.symmetric_difference(b) | In exactly one |
Python
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
print(a & b) # {3, 4}
print(a - b) # {1, 2}
print(a ^ b) # {1, 2, 5}
print(a.issubset({1, 2, 3, 4, 5})) # True
print(a.isdisjoint({9})) # TruePractical Uses
Python
# 1) 两批 ID 的差异(新增 / 删除)
old_ids = {1, 2, 3}
new_ids = {2, 3, 4}
added, removed = new_ids - old_ids, old_ids - new_ids
# 2) 去重后再求交,比双重循环快一个量级
banned = {"spam", "ads"}
hits = [w for w in words if w in banned]
# 3) frozenset 可哈希,能当字典键
cache = {}
cache[frozenset({"a", "b"})] = "combo"Set elements must be hashable. A list of lists cannot be deduped with set() — convert inner items to tuples first.
基础
Python
tags = {"python", "backend", "python"} # {'python', 'backend'},自动去重
empty = set() # 注意:{} 是空字典,不是空集合
tags.add("api")
tags.discard("backend") # 不存在也不报错(remove 会抛 KeyError)
print("api" in tags) # O(1)
print(len(tags))保序去重
集合不保序。要在去重的同时保留首次出现顺序,用 dict.fromkeys。
Python
items = ["b", "a", "b", "c", "a"]
print(list(set(items))) # 顺序不可预测
print(list(dict.fromkeys(items))) # ['b', 'a', 'c'] 保序去重集合运算
| 运算 | 运算符 | 方法 | 结果 |
|---|---|---|---|
| 并集 | a | b | a.union(b) | 在 a 或 b 中 |
| 交集 | a & b | a.intersection(b) | 同时在两者中 |
| 差集 | a - b | a.difference(b) | 在 a 不在 b |
| 对称差 | a ^ b | a.symmetric_difference(b) | 只在一个中 |
Python
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
print(a & b) # {3, 4}
print(a - b) # {1, 2}
print(a ^ b) # {1, 2, 5}
print(a.issubset({1, 2, 3, 4, 5})) # True
print(a.isdisjoint({9})) # True实用场景
Python
# 1) 两批 ID 的差异(新增 / 删除)
old_ids = {1, 2, 3}
new_ids = {2, 3, 4}
added, removed = new_ids - old_ids, old_ids - new_ids
# 2) 去重后再求交,比双重循环快一个量级
banned = {"spam", "ads"}
hits = [w for w in words if w in banned]
# 3) frozenset 可哈希,能当字典键
cache = {}
cache[frozenset({"a", "b"})] = "combo"集合元素必须可哈希。列表套列表无法直接 set() 去重 —— 先把内层转成元组。