Python 集合(Set)详细介绍

1. 什么是集合

集合是Python中的一种无序、不重复元素的数据结构。

# 创建集合
my_set = {1, 2, 3, 4, 5}
empty_set = set()  # 注意:不能使用 {} 创建空集合,{}创建的是空字典

print(my_set)  # 输出: {1, 2, 3, 4, 5}
print(type(my_set))  # 输出: <class 'set'>

2. 集合的创建方式

# 方法1: 使用花括号
set1 = {1, 2, 3, 4}

# 方法2: 使用set()构造函数
set2 = set([1, 2, 3, 4])  # 从列表
set3 = set("hello")       # 从字符串,会自动去重
set4 = set((1, 2, 3))     # 从元组

print(set3)  # 输出: {'h', 'e', 'l', 'o'}

3. 集合的基本特性

# 无序性 - 元素没有固定顺序
set_a = {3, 1, 4, 1, 5, 9}
print(set_a)  # 输出可能是: {1, 3, 4, 5, 9}

# 唯一性 - 自动去重
duplicate_set = {1, 2, 2, 3, 3, 3, 4}
print(duplicate_set)  # 输出: {1, 2, 3, 4}

# 可哈希性 - 集合元素必须是不可变类型
valid_set = {1, "hello", (1, 2)}  # 正确
# invalid_set = {1, [1, 2]}       # 错误: 列表不可哈希

4. 集合的常用操作

添加元素

my_set = {1, 2, 3}

# add() - 添加单个元素
my_set.add(4)
print(my_set)  # 输出: {1, 2, 3, 4}

# update() - 添加多个元素
my_set.update([5, 6, 7])
print(my_set)  # 输出: {1, 2, 3, 4, 5, 6, 7}

删除元素

my_set = {1, 2, 3, 4, 5}

# remove() - 删除指定元素,元素不存在会报错
my_set.remove(3)
print(my_set)  # 输出: {1, 2, 4, 5}

# discard() - 删除指定元素,元素不存在不会报错
my_set.discard(2)
my_set.discard(10)  # 不会报错
print(my_set)  # 输出: {1, 4, 5}

# pop() - 随机删除并返回一个元素
element = my_set.pop()
print(f"删除的元素: {element}, 剩余集合: {my_set}")

# clear() - 清空集合
my_set.clear()
print(my_set)  # 输出: set()

5. 集合运算

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# 并集 (Union)
print(A | B)        # 方法1: 使用 | 运算符
print(A.union(B))   # 方法2: 使用 union() 方法
# 输出: {1, 2, 3, 4, 5, 6, 7, 8}

# 交集 (Intersection)
print(A & B)              # 方法1: 使用 & 运算符
print(A.intersection(B))  # 方法2: 使用 intersection() 方法
# 输出: {4, 5}

# 差集 (Difference)
print(A - B)              # 方法1: 使用 - 运算符
print(A.difference(B))    # 方法2: 使用 difference() 方法
# 输出: {1, 2, 3}

# 对称差集 (Symmetric Difference)
print(A ^ B)                      # 方法1: 使用 ^ 运算符
print(A.symmetric_difference(B))  # 方法2: 使用 symmetric_difference() 方法
# 输出: {1, 2, 3, 6, 7, 8}

6. 集合关系判断

A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
C = {4, 5, 6}

# 子集判断
print(A.issubset(B))     # True, A是B的子集
print(A <= B)           # True

# 真子集判断
print(A < B)            # True, A是B的真子集

# 超集判断
print(B.issuperset(A))  # True, B是A的超集
print(B >= A)           # True

# 交集判断
print(A.isdisjoint(C))  # True, A和C没有交集

7. 集合推导式

# 创建平方数的集合
squares = {x**2 for x in range(10)}
print(squares)  # 输出: {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

# 带条件的集合推导式
even_squares = {x**2 for x in range(10) if x % 2 == 0}
print(even_squares)  # 输出: {0, 4, 16, 36, 64}

8. 冻结集合 (Frozenset)

# 创建不可变集合
frozen = frozenset([1, 2, 3, 4])
print(frozen)  # 输出: frozenset({1, 2, 3, 4})

# frozenset可以用作字典的键或另一个集合的元素
dict_with_frozenset = {frozenset([1, 2]): "value"}
set_with_frozenset = {frozenset([1, 2]), frozenset([3, 4])}

9. 实际应用场景

数据去重

# 列表去重
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique_numbers = list(set(numbers))
print(unique_numbers)  # 输出: [1, 2, 3, 4]

成员测试

# 集合的成员测试比列表快很多
vip_users = {'Alice', 'Bob', 'Charlie'}
user = 'Alice'
print(user in vip_users)  # 输出: True

寻找差异

# 比较两个列表的差异
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

only_in_list1 = set(list1) - set(list2)
only_in_list2 = set(list2) - set(list1)

print(f"只在list1中: {only_in_list1}")  # 输出: {1, 2, 3}
print(f"只在list2中: {only_in_list2}")  # 输出: {6, 7, 8}

10. 集合方法总结

方法 描述
add(x) 添加元素x
remove(x) 删除元素x,不存在则报错
discard(x) 删除元素x,不存在不报错
pop() 随机删除并返回一个元素
clear() 清空集合
union() 返回并集
intersection() 返回交集
difference() 返回差集
symmetric_difference() 返回对称差集
issubset() 判断子集
issuperset() 判断超集
isdisjoint() 判断是否无交集

集合是Python中非常实用的数据结构,特别适合需要去重、快速成员测试和数学集合运算的场景。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐