Python3 集合

Unordered unique elements, O(1) membership, set algebra, and frozenset.

Beginner
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

OperationOperatorMethodResult
Uniona | ba.union(b)In a or b
Intersectiona & ba.intersection(b)In both
Differencea - ba.difference(b)In a, not b
Symmetric diffa ^ ba.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}))             # True

Practical 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.

Friends & Partners