集合(Set) #
集合是无序、不重复元素的可变集合。
一、创建集合 #
1.1 基本创建 #
python
# 空集合(注意:{}是空字典)
empty = set() # 正确
# empty = {} # 这是空字典!
# 带元素
numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "cherry"}
# 自动去重
duplicates = {1, 2, 2, 3, 3, 3}
print(duplicates) # {1, 2, 3}
# 混合类型
mixed = {1, "hello", 3.14, (1, 2)} # 元组可以作为元素
# mixed = {1, [1, 2]} # 列表不能作为元素(不可哈希)
1.2 使用set()函数 #
python
# 从列表创建
list_data = [1, 2, 2, 3, 3, 3]
unique = set(list_data)
print(unique) # {1, 2, 3}
# 从字符串创建
chars = set("hello")
print(chars) # {'h', 'e', 'l', 'o'}
# 从元组创建
tuple_data = (1, 2, 2, 3)
unique = set(tuple_data)
1.3 集合推导式 #
python
# 基本推导式
squares = {x ** 2 for x in range(5)}
print(squares) # {0, 1, 4, 9, 16}
# 带条件
evens = {x for x in range(10) if x % 2 == 0}
print(evens) # {0, 2, 4, 6, 8}
二、集合特点 #
2.1 无序性 #
python
fruits = {"apple", "banana", "cherry"}
# 不能通过索引访问
# print(fruits[0]) # TypeError
# 每次输出顺序可能不同
print(fruits) # 顺序不确定
2.2 唯一性 #
python
# 自动去重
numbers = {1, 2, 2, 3, 3, 3}
print(numbers) # {1, 2, 3}
# 利用去重特性
items = [1, 2, 2, 3, 3, 3, 4, 4]
unique_items = list(set(items))
print(unique_items) # [1, 2, 3, 4](顺序可能改变)
# 保持顺序去重
def unique_ordered(items):
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return result
2.3 元素必须可哈希 #
python
# 不可变类型可以作为元素
valid = {1, "hello", 3.14, (1, 2), frozenset([1, 2])}
# 可变类型不能作为元素
# invalid = { [1, 2] } # TypeError: list不可哈希
# invalid = { {1, 2} } # TypeError: set不可哈希
# invalid = { {"a": 1} } # TypeError: dict不可哈希
三、访问集合 #
3.1 遍历集合 #
python
fruits = {"apple", "banana", "cherry"}
# 遍历元素
for fruit in fruits:
print(fruit)
# 带索引遍历(使用enumerate)
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
3.2 成员检查 #
python
fruits = {"apple", "banana", "cherry"}
# in检查(效率高,O(1))
print("apple" in fruits) # True
print("orange" in fruits) # False
print("orange" not in fruits) # True
四、修改集合 #
4.1 添加元素 #
python
fruits = {"apple", "banana"}
# add:添加单个元素
fruits.add("cherry")
print(fruits) # {'apple', 'banana', 'cherry'}
# 添加已存在元素(无效果)
fruits.add("apple") # 不会重复
# update:添加多个元素
fruits.update(["date", "elderberry"])
print(fruits)
# update可以接受任何可迭代对象
fruits.update({"fig", "grape"})
fruits.update("hi") # 添加 'h' 和 'i'
4.2 删除元素 #
python
fruits = {"apple", "banana", "cherry", "date"}
# remove:删除元素(不存在会报错)
fruits.remove("banana")
print(fruits) # {'apple', 'cherry', 'date'}
# fruits.remove("orange") # KeyError
# discard:删除元素(不存在不报错)
fruits.discard("cherry")
fruits.discard("orange") # 不报错
# pop:随机删除并返回一个元素
removed = fruits.pop()
print(removed)
# clear:清空集合
fruits.clear()
print(fruits) # set()
4.3 复制集合 #
python
original = {1, 2, 3}
# copy方法
copied = original.copy()
# set函数
copied = set(original)
# 注意:集合元素是不可变的,所以没有深拷贝问题
五、集合运算 #
5.1 并集 #
python
a = {1, 2, 3}
b = {3, 4, 5}
# 使用 |
union = a | b
print(union) # {1, 2, 3, 4, 5}
# 使用 union 方法
union = a.union(b)
print(union) # {1, 2, 3, 4, 5}
# union 可以接受任何可迭代对象
union = a.union([3, 4, 5])
# |= 原地更新
a |= b # 或 a.update(b)
5.2 交集 #
python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
# 使用 &
intersection = a & b
print(intersection) # {3, 4}
# 使用 intersection 方法
intersection = a.intersection(b)
print(intersection) # {3, 4}
# &= 原地更新
a &= b # 或 a.intersection_update(b)
5.3 差集 #
python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
# 使用 -
diff = a - b
print(diff) # {1, 2}(在a但不在b)
diff = b - a
print(diff) # {5, 6}(在b但不在a)
# 使用 difference 方法
diff = a.difference(b)
print(diff) # {1, 2}
# -= 原地更新
a -= b # 或 a.difference_update(b)
5.4 对称差集 #
python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
# 使用 ^
symmetric_diff = a ^ b
print(symmetric_diff) # {1, 2, 5, 6}(在a或b但不同时在)
# 使用 symmetric_difference 方法
symmetric_diff = a.symmetric_difference(b)
print(symmetric_diff) # {1, 2, 5, 6}
# ^= 原地更新
a ^= b # 或 a.symmetric_difference_update(b)
5.5 运算符总结 #
| 运算 | 运算符 | 方法 | 原地更新 |
|---|---|---|---|
| 并集 | | |
union() |
update() |
| 交集 | & |
intersection() |
intersection_update() |
| 差集 | - |
difference() |
difference_update() |
| 对称差 | ^ |
symmetric_difference() |
symmetric_difference_update() |
六、集合判断方法 #
6.1 子集和超集 #
python
a = {1, 2, 3}
b = {1, 2, 3, 4, 5}
# 子集判断
print(a.issubset(b)) # True
print(a <= b) # True
print(a < b) # True(真子集)
# 超集判断
print(b.issuperset(a)) # True
print(b >= a) # True
print(b > a) # True(真超集)
6.2 无交集判断 #
python
a = {1, 2, 3}
b = {4, 5, 6}
c = {3, 4, 5}
# 判断是否无交集
print(a.isdisjoint(b)) # True
print(a.isdisjoint(c)) # False(有共同元素3)
6.3 相等判断 #
python
a = {1, 2, 3}
b = {3, 2, 1}
# 集合相等(顺序无关)
print(a == b) # True
print(a != b) # False
七、不可变集合(frozenset) #
7.1 创建frozenset #
python
# 创建不可变集合
fs = frozenset([1, 2, 3])
print(fs) # frozenset({1, 2, 3})
# 不能修改
# fs.add(4) # AttributeError
# fs.remove(1) # AttributeError
7.2 作为字典键或集合元素 #
python
# 普通集合不能作为字典键
# d = {{1, 2}: "value"} # TypeError
# frozenset可以作为键
d = {frozenset([1, 2]): "value"}
print(d[frozenset([1, 2])]) # "value"
# frozenset可以作为集合元素
nested = {frozenset([1, 2]), frozenset([3, 4])}
print(nested) # {frozenset({1, 2}), frozenset({3, 4})}
7.3 frozenset运算 #
python
a = frozenset([1, 2, 3])
b = frozenset([3, 4, 5])
# 支持集合运算(返回新frozenset)
print(a | b) # frozenset({1, 2, 3, 4, 5})
print(a & b) # frozenset({3})
print(a - b) # frozenset({1, 2})
八、集合应用场景 #
8.1 去重 #
python
# 列表去重
items = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(items))
print(unique) # [1, 2, 3, 4](顺序可能改变)
# 保持顺序去重
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
seen.add(item)
yield item
unique = list(dedupe(items))
8.2 成员检查 #
python
# 集合的成员检查比列表快得多
items = range(100000)
items_list = list(items)
items_set = set(items)
# 列表:O(n)
# "99999" in items_list # 较慢
# 集合:O(1)
# "99999" in items_set # 很快
8.3 找共同元素 #
python
# 找两个列表的共同元素
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common = set(list1) & set(list2)
print(common) # {4, 5}
8.4 找唯一元素 #
python
# 找只在一个列表中的元素
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
# 在list1但不在list2
unique_to_list1 = set(list1) - set(list2)
print(unique_to_list1) # {1, 2, 3}
# 在任一列表但不同时存在
unique = set(list1) ^ set(list2)
print(unique) # {1, 2, 3, 6, 7, 8}
九、集合方法汇总 #
9.1 修改方法 #
| 方法 | 描述 |
|---|---|
add(elem) |
添加元素 |
remove(elem) |
删除元素(不存在报错) |
discard(elem) |
删除元素(不存在不报错) |
pop() |
随机删除并返回 |
clear() |
清空集合 |
update(iterable) |
添加多个元素 |
9.2 运算方法 #
| 方法 | 描述 | 等价运算符 |
|---|---|---|
union() |
并集 | | |
intersection() |
交集 | & |
difference() |
差集 | - |
symmetric_difference() |
对称差 | ^ |
9.3 判断方法 #
| 方法 | 描述 |
|---|---|
issubset() |
是否为子集 |
issuperset() |
是否为超集 |
isdisjoint() |
是否无交集 |
十、总结 #
| 特点 | 说明 |
|---|---|
| 无序 | 元素没有固定顺序 |
| 唯一 | 元素不能重复 |
| 可变 | 可以添加删除元素 |
| 可哈希 | 元素必须可哈希 |
集合 vs 列表:
| 特性 | 集合 | 列表 |
|---|---|---|
| 有序性 | 无序 | 有序 |
| 唯一性 | 唯一 | 可重复 |
| 成员检查 | O(1) 快 | O(n) 慢 |
| 索引访问 | 不支持 | 支持 |
| 数学运算 | 支持 | 不支持 |
最后更新:2026-03-16