Python 集合 (Set)
集合(Sets)是 Python 中用于存储唯一元素集合的基础数据结构。
当你需要确保数据中不存在重复值,或者需要执行诸如并集、交集和差集等数学集合运算时,它们特别有用。
1. 理解集合 (Sets)
集合是一个包含独立且可哈希 (hashable) 对象的无序集合。
- 无序 (Unordered):这意味着集合中的元素没有特定的顺序或索引,这与列表 (lists) 或元组 (tuples) 不同。
- 唯一 (Distinct):这意味着一个集合只能包含唯一的元素;重复的值会被自动丢弃。
- 可哈希 (Hashable):这意味着集合中的元素必须是不可变的(例如数字、字符串、元组)。列表和字典是不可哈希的,因此不能作为集合的元素。
2. 创建集合
在 Python 中,主要有两种创建集合的方法:
2.1 使用花括号 {}
# 创建一个整数集合
my_set = {1, 2, 3, 4, 5}
print(my_set) # 输出: {1, 2, 3, 4, 5}
# 创建一个字符串集合
string_set = {"apple", "banana", "cherry"}
print(string_set) # 输出: {'apple', 'banana', 'cherry'} (输出顺序可能会变化)2.2 使用 set() 构造函数
# 从列表创建一个集合
my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
print(my_set) # 输出: {1, 2, 3, 4, 5} (重复项被自动移除)
# 创建一个空集合
empty_set = set()
print(empty_set) # 输出: set()重要提示: 使用空的花括号 {} 创建的是一个空字典,而不是空集合。要创建一个空集合,你必须使用 set() 构造函数。
3. 添加和删除元素
集合是可变的(mutable),这意味着在集合创建后,你可以添加和删除元素。
3.1 添加元素
add(element): 向集合中添加单个元素。
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # 输出: {1, 2, 3, 4}
my_set.add(3) # 添加一个已存在的元素不会有任何效果
print(my_set) # 输出: {1, 2, 3, 4}update(iterable): 将一个可迭代对象(如列表、元组、另一个集合)中的多个元素添加到集合中。
my_set = {1, 2, 3}
my_set.update([4, 5, 6])
print(my_set) # 输出: {1, 2, 3, 4, 5, 6}
my_set.update((7, 8))
print(my_set) # 输出: {1, 2, 3, 4, 5, 6, 7, 8}
my_set.update({9, 10})
print(my_set) # 输出: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}3.2 删除元素
remove(element): 从集合中删除指定的元素。如果找不到该元素,会引发KeyError报错。
my_set = {1, 2, 3, 4}
my_set.remove(3)
print(my_set) # 输出: {1, 2, 4}
# my_set.remove(5) # 会引发 KeyError: 5 (找不到元素)discard(element): 从集合中删除指定的元素(如果存在)。如果找不到该元素,不会引发报错。
my_set = {1, 2, 3, 4}
my_set.discard(3)
print(my_set) # 输出: {1, 2, 4}
my_set.discard(5) # 不会引发错误
print(my_set) # 输出: {1, 2, 4}pop(): 移除并返回集合中的一个任意元素。如果集合为空,则引发KeyError。因为集合是无序的,所以你无法预测哪个元素会被移除。
my_set = {1, 2, 3, 4}
element = my_set.pop()
print(element) # 输出: (例如 1 - 输出结果可能会变化)
print(my_set) # 输出: (例如 {2, 3, 4} - 输出结果可能会变化)
empty_set = set()
# empty_set.pop() # 会引发 KeyError: 'pop from an empty set'clear(): 移除集合中的所有元素,使其成为一个空集合。
my_set = {1, 2, 3, 4}
my_set.clear()
print(my_set) # 输出: set()4. 集合的数学运算
集合支持多种数学运算,这在许多编程场景中都非常实用。
4.1 并集 (Union)
两个集合的并集是一个包含两个集合中所有元素的新集合。
- 使用
|运算符:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set) # 输出: {1, 2, 3, 4, 5}- 使用
union()方法:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # 输出: {1, 2, 3, 4, 5}4.2 交集 (Intersection)
两个集合的交集是一个只包含两个集合中共有元素的新集合。
- 使用
&运算符:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1 & set2
print(intersection_set) # 输出: {3}- 使用
intersection()方法:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set) # 输出: {3}4.3 差集 (Difference)
两个集合的差集是一个新集合,包含存在于第一个集合中但不存在于第二个集合中的元素。
- 使用
-运算符:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1 - set2
print(difference_set) # 输出: {1, 2}- 使用
difference()方法:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set) # 输出: {1, 2}4.4 对称差集 (Symmetric Difference)
两个集合的对称差集是一个新集合,包含存在于两个集合中任意一个集合里的元素,但不包含它们的交集(即只在其中一个集合里出现的元素)。
- 使用
^运算符:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set) # 输出: {1, 2, 4, 5}- 使用
symmetric_difference()方法:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # 输出: {1, 2, 4, 5}4.5 子集与超集 (Subset and Superset)
子集 (Subset): 如果一个集合的所有元素都包含在另一个集合中,则该集合是另一个集合的子集。
- 使用
<=运算符 或issubset()方法:
set1 = {1, 2}
set2 = {1, 2, 3}
print(set1 <= set2) # 输出: True (set1 是 set2 的子集)
print(set2 <= set1) # 输出: False (set2 不是 set1 的子集)
print(set1.issubset(set2)) # 输出: True超集 (Superset): 如果一个集合包含了另一个集合的所有元素,则该集合是另一个集合的超集。
- 使用
>=运算符 或issuperset()方法:
set1 = {1, 2, 3}
set2 = {1, 2}
print(set1 >= set2) # 输出: True (set1 是 set2 的超集)
print(set2 >= set1) # 输出: False (set2 不是 set1 的超集)
print(set1.issuperset(set2)) # 输出: True5. 集合推导式 (Set Comprehension)
与列表推导式类似,集合推导式提供了一种创建集合的简洁方法。
# 创建一个包含 1 到 5 数字平方的集合
squares = {x**2 for x in range(1, 6)}
print(squares) # 输出: {1, 4, 9, 16, 25}
# 从一个列表中提取偶数创建一个新集合
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = {x for x in numbers if x % 2 == 0}
print(even_numbers) # 输出: {2, 4, 6, 8, 10}6. 实际案例与演示
让我们探讨一些实际例子,看看如何使用集合来解决常见的编程问题。
6.1 从列表中移除重复项
集合最常见的用途之一就是从列表中去除重复的元素。
my_list = [1, 2, 2, 3, 4, 4, 5, 5, 5]
unique_list = list(set(my_list)) # 将集合转换回列表
print(unique_list) # 输出: [1, 2, 3, 4, 5]6.2 寻找两个列表的共同元素
可以使用集合高效地找到两个列表之间的共同元素。
list1 = [1, 2, 3, 4, 5]
list2 = [3, 5, 6, 7, 8]
set1 = set(list1)
set2 = set(list2)
common_elements = list(set1.intersection(set2))
print(common_elements) # 输出: [3, 5]6.3 检查成员资格 (Membership)
集合提供了一种非常高效的方法来检查集合中是否存在某个特定元素。
my_set = {1, 2, 3, 4, 5}
print(3 in my_set) # 输出: True
print(6 in my_set) # 输出: False6.4 分析文本数据
集合可用于分析文本数据,例如查找文档中不重复的单词。
text = "This is a sample text. This text is used to demonstrate set operations."
words = text.lower().split() # 转换为小写并拆分成单词列表
unique_words = set(words)
print(unique_words)
# 输出: {'a', 'is', 'operations.', 'this', 'text', 'sample', 'to', 'used', 'demonstrate', 'set'}
print(len(unique_words)) # 输出: 10