Python 集合(set)
集合(set
)是 Python 中的一种无序且不重复的容器,它可以存储多个元素,并自动去除重复值。集合适合用于处理需要去重或者集合运算(如交集、并集等)的场景。
1. 什么是集合?
特点:
- 无序性:集合中的元素没有固定的顺序,无法通过索引访问。
- 唯一性:集合中的元素是唯一的,不允许重复。
- 可变性:集合本身可以修改,但集合中的元素必须是不可变对象(如数字、字符串、元组等)。
定义: 使用花括号
{}
或内置函数set()
来创建集合,元素之间用逗号,
分隔。
示例:定义集合
# 定义一个集合
fruits = {"苹果", "香蕉", "橙子"}
# 创建一个空集合
empty_set = set() # 注意:{} 是空字典
# 自动去重
numbers = {1, 2, 2, 3, 3, 4}
print(numbers) # 输出:{1, 2, 3, 4}
2. 集合的操作
1) 添加与删除元素
- 添加元素:使用
add()
方法。 - 删除元素:使用
remove()
或discard()
方法。
fruits = {"苹果", "香蕉"}
# 添加
fruits.add("橙子")
print(fruits) # 输出:{"苹果", "香蕉", "橙子"}
# 删除(若元素不存在,remove 会报错,discard 不报错)
fruits.remove("香蕉")
# fruits.remove("葡萄") # 报错:KeyError
fruits.discard("葡萄") # 不报错
2) 检查元素
- 使用
in
判断某个元素是否在集合中。
fruits = {"苹果", "香蕉", "橙子"}
print("苹果" in fruits) # 输出:True
print("葡萄" in fruits) # 输出:False
3) 清空集合
- 使用
clear()
方法清空集合。
fruits = {"苹果", "香蕉"}
fruits.clear()
print(fruits) # 输出:set()
3. 集合运算
集合是数学中集合的编程实现,支持常见的交集、并集、差集、对称差集等操作。
运算方式 | 方法/操作符 | 示例 | 结果 |
---|---|---|---|
交集 | & 或 intersection() |
a & b / a.intersection(b) |
两集合的公共元素 |
并集 | | 或 union() |
a | b / a.union(b) |
两集合的所有元素 |
差集 | - 或 difference() |
a - b / a.difference(b) |
在 a 而不在 b 的元素 |
对称差集 | ^ 或 symmetric_difference() |
a ^ b / a.symmetric_difference(b) |
两集合的非公共元素 |
示例:集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
# 交集
print(a & b) # 输出:{3, 4}
# 并集
print(a | b) # 输出:{1, 2, 3, 4, 5, 6}
# 差集
print(a - b) # 输出:{1, 2}
print(b - a) # 输出:{5, 6}
# 对称差集
print(a ^ b) # 输出:{1, 2, 5, 6}
4. 集合的遍历
集合可以使用 for
循环进行遍历。
fruits = {"苹果", "香蕉", "橙子"}
for fruit in fruits:
print(fruit)
注意:集合是无序的,因此输出顺序可能与定义时不同。
5. 常用内置方法
方法 | 描述 | 示例 |
---|---|---|
add(item) |
向集合中添加元素 | s.add(5) |
remove(item) |
删除指定元素,不存在时抛出异常 | s.remove(5) |
discard(item) |
删除指定元素,不存在时不抛出异常 | s.discard(5) |
pop() |
随机删除并返回集合中的一个元素 | s.pop() |
clear() |
清空集合 | s.clear() |
copy() |
返回集合的浅拷贝 | new_set = s.copy() |
intersection(other) |
返回交集 | s.intersection(t) |
union(other) |
返回并集 | s.union(t) |
difference(other) |
返回差集 | s.difference(t) |
symmetric_difference(other) |
返回对称差集 | s.symmetric_difference(t) |
6. 集合的应用场景
数据去重:快速过滤掉重复元素。
numbers = [1, 2, 2, 3, 3, 4] unique_numbers = set(numbers) print(unique_numbers) # 输出:{1, 2, 3, 4}
集合运算:用于数学集合操作,如交集、并集等。
快速查找:集合的查找效率比列表高。
items = {"苹果", "香蕉", "橙子"} print("苹果" in items) # 输出:True
过滤重复用户:比如统计访问过的网站用户。
7. 注意事项
集合中的元素必须是不可变的,因此不能存放列表、集合等可变对象。
# 错误示例 # my_set = {[1, 2], 3} # TypeError
空集合的定义必须使用
set()
,直接{}
会创建字典。empty_set = set() # 空集合 empty_dict = {} # 空字典
8. 总结
集合是一种无序且唯一的数据结构,适用于去重、快速查找和数学集合运算。通过掌握集合的基本操作和方法,可以有效解决实际编程中的一些问题。