在 Python 中使用集合

PythonBeginner
立即练习

介绍

在这个 Lab 中,你将获得关于 Python 中集合(sets)的实践经验。集合是一种基本的数据结构,用于存储唯一的、无序的元素。它们在检查元素是否存在于集合中以及执行数学集合运算等任务时非常高效。

你将学习如何创建集合、添加和移除元素,以及执行常见的操作,如并集(union)、交集(intersection)和差集(difference)。最后,你将通过使用集合来轻松移除列表中的重复项,从而看到集合的一个实际应用。

这是一个实验(Guided Lab),提供逐步指导来帮助你学习和实践。请仔细按照说明完成每个步骤,获得实际操作经验。根据历史数据,这是一个 初级 级别的实验,完成率为 100%。获得了学习者 100% 的好评率。

创建集合并添加元素

在第一步中,你将学习如何创建集合以及向其中添加新元素。集合是唯一项的集合,这意味着它们会自动丢弃任何重复项。

你的环境中包含一个名为 set_basics.py 的空文件。使用编辑器左侧的文件浏览器,找到并打开 ~/project/set_basics.py

将以下 Python 代码添加到文件中。此代码演示了几种创建集合的方法。

## 方法 1: 使用花括号 {}
## 这会创建一个带有初始元素的集合。
my_set = {'apple', 'banana', 'cherry'}
print("Set created with braces:", my_set)
print("Type of my_set:", type(my_set))

## 注意:集合会自动移除重复的元素。
duplicate_set = {'apple', 'banana', 'apple'}
print("Set with duplicates:", duplicate_set)

## 方法 2: 对可迭代对象(如字符串)使用 set() 构造函数
## 这会从字符串中唯一的字符创建一个集合。
char_set = set('hello world')
print("Set from a string:", char_set)

## 方法 3: 创建一个空集合
## 你必须使用 set() 来创建一个空集合。{} 创建的是一个空字典(dictionary)。
empty_set = set()
print("An empty set:", empty_set)
print("Type of empty_set:", type(empty_set))

保存文件。现在,在你的编辑器中打开一个终端(你可以使用菜单:Terminal -> New Terminal),并使用以下命令运行你的脚本。

python ~/project/set_basics.py

你将看到类似以下的输出。请注意,集合中元素的顺序不保证,并且重复项已被移除。

Set created with braces: {'cherry', 'apple', 'banana'}
Type of my_set: <class 'set'>
Set with duplicates: {'banana', 'apple'}
Set from a string: {'d', 'l', 'o', 'r', 'w', ' ', 'h', 'e'}
An empty set: set()
Type of empty_set: <class 'set'>

接下来,让我们向现有集合中添加新元素。你可以使用 add() 方法添加单个元素,或使用 update() 方法添加多个元素。

将以下代码添加到 set_basics.py 文件的底部

## --- 添加元素 ---
fruits = {'apple', 'banana'}
print("\nOriginal fruits set:", fruits)

## 使用 add() 添加单个元素
fruits.add('orange')
print("After adding 'orange':", fruits)

## 如果元素已存在,add() 不会产生任何影响
fruits.add('apple')
print("After adding 'apple' again:", fruits)

## 使用 update() 从可迭代对象(如列表)中添加多个元素
fruits.update(['mango', 'grape'])
print("After updating with a list:", fruits)

再次保存文件,并在终端中运行更新后的脚本。

python ~/project/set_basics.py

输出现在将包含添加元素的结果。

Set created with braces: {'cherry', 'apple', 'banana'}
Type of my_set: <class 'set'>
Set with duplicates: {'banana', 'apple'}
Set from a string: {'d', 'l', 'o', 'r', 'w', ' ', 'h', 'e'}
An empty set: set()
Type of empty_set: <class 'set'>

Original fruits set: {'banana', 'apple'}
After adding 'orange': {'banana', 'orange', 'apple'}
After adding 'apple' again: {'banana', 'orange', 'apple'}
After updating with a list: {'grape', 'mango', 'banana', 'orange', 'apple'}

你现在已经学会了如何创建集合以及如何通过添加新元素来修改它们。

从集合中移除元素

在这一步中,你将学习从集合中移除元素的各种方法。由于集合是无序的,你不能使用索引来移除项。相反,Python 提供了专门的方法来实现此目的。

在你的 ~/project 目录中找到并打开文件 set_removal.py

将以下代码添加到文件中。它演示了 remove()discard()pop()clear() 方法。

## --- 移除元素 ---
my_set = {'a', 'b', 'c', 'd', 'e'}
print("Original set:", my_set)

## 方法 1: remove()
## 此方法移除指定的元素。如果找不到该元素,它会引发一个 KeyError。
my_set.remove('b')
print("After removing 'b':", my_set)
## 下一行代码将导致错误:my_set.remove('z')

## 方法 2: discard()
## 此方法也移除指定的元素,但如果找不到该元素,它不会引发错误。
print("\nStarting set for discard:", my_set)
my_set.discard('c')
print("After discarding 'c':", my_set)
my_set.discard('z') ## 'z' 不在集合中,但不会发生错误。
print("After discarding 'z' (non-existent):", my_set)

## 方法 3: pop()
## 此方法从集合中移除并返回一个任意元素。
## 由于集合是无序的,你不知道哪个元素会被弹出。
print("\nStarting set for pop:", my_set)
popped_item = my_set.pop()
print("Popped item:", popped_item)
print("Set after pop():", my_set)

## 方法 4: clear()
## 此方法移除集合中的所有元素,使集合变为空集。
print("\nStarting set for clear:", my_set)
my_set.clear()
print("Set after clear():", my_set)

保存文件。现在,从终端运行脚本。

python ~/project/set_removal.py

你的输出应该与此类似。由于集合是无序的,每次运行脚本时,被 pop() 移除的元素可能会有所不同。

Original set: {'d', 'c', 'e', 'a', 'b'}
After removing 'b': {'d', 'c', 'e', 'a'}

Starting set for discard: {'d', 'c', 'e', 'a'}
After discarding 'c': {'d', 'e', 'a'}
After discarding 'z' (non-existent): {'d', 'e', 'a'}

Starting set for pop: {'d', 'e', 'a'}
Popped item: d
Set after pop(): {'e', 'a'}

Starting set for clear: {'e', 'a'}
Set after clear(): set()

你现在知道了从集合中移除元素的主要方法,并理解了 remove()discard() 之间的重要区别。

执行集合操作

集合在执行数学运算(如并集、交集和差集)方面特别强大。在这一步中,你将学习如何在 Python 中执行这些运算。

在你的 ~/project 目录中找到并打开文件 set_operations.py

将以下代码添加到文件中。此代码定义了两个集合,然后对它们执行三种主要的集合运算。

set_a = {'a', 'b', 'c', 'd'}
set_b = {'c', 'd', 'e', 'f'}

print("Set A:", set_a)
print("Set B:", set_b)

## --- 并集 (Union) ---
## 并集包含来自两个集合的所有唯一元素。
## 你可以使用 | 运算符或 .union() 方法。
union_set_op = set_a | set_b
union_set_method = set_a.union(set_b)
print("\nUnion with | operator:", union_set_op)
print("Union with .union() method:", union_set_method)

## --- 交集 (Intersection) ---
## 交集只包含两个集合共有的元素。
## 你可以使用 & 运算符或 .intersection() 方法。
intersection_set_op = set_a & set_b
intersection_set_method = set_a.intersection(set_b)
print("\nIntersection with & operator:", intersection_set_op)
print("Intersection with .intersection() method:", intersection_set_method)

## --- 差集 (Difference) ---
## 差集包含在第一个集合中但不在第二个集合中的元素。
## 你可以使用 - 运算符或 .difference() 方法。
difference_set_op = set_a - set_b
difference_set_method = set_a.difference(set_b)
print("\nDifference (A - B) with - operator:", difference_set_op)
print("Difference (A - B) with .difference() method:", difference_set_method)

## 注意,差集的顺序很重要
difference_b_a = set_b - set_a
print("Difference (B - A):", difference_b_a)

保存文件并在终端中执行它。

python ~/project/set_operations.py

输出将清晰地显示每次运算的结果。

Set A: {'d', 'c', 'a', 'b'}
Set B: {'d', 'c', 'f', 'e'}

Union with | operator: {'d', 'c', 'f', 'e', 'a', 'b'}
Union with .union() method: {'d', 'c', 'f', 'e', 'a', 'b'}

Intersection with & operator: {'d', 'c'}
Intersection with .intersection() method: {'d', 'c'}

Difference (A - B) with - operator: {'a', 'b'}
Difference (A - B) with .difference() method: {'a', 'b'}
Difference (B - A): {'f', 'e'}

你已成功使用运算符符号和方法对集合执行了并集、交集和差集运算。

使用集合从列表中移除重复项

集合最常见和最实用的用途之一是快速移除列表中的重复元素。因为集合只能包含唯一的元素,所以将列表转换为集合再转换回列表是一种简单而高效的实现方式。

在你的 ~/project 目录中找到并打开本次实验的最后一个文件 remove_duplicates.py

将以下代码添加到文件中。

## 一个包含多个重复数字的列表
numbers_list = [1, 5, 2, 3, 5, 1, 4, 2, 2, 5]
print("Original list with duplicates:", numbers_list)

## 步骤 1: 将列表转换为集合。
## 这会自动移除所有重复的元素。
unique_numbers_set = set(numbers_list)
print("Set created from list (duplicates gone):", unique_numbers_set)

## 步骤 2: 将集合转换回列表。
## 新列表将只包含唯一的元素。
unique_numbers_list = list(unique_numbers_set)
print("Final list with duplicates removed:", unique_numbers_list)

## 注意:此过程不会保留元素的原始顺序,因为集合是一种无序的数据结构。

保存文件并在终端中运行它。

python ~/project/remove_duplicates.py

输出演示了整个过程,显示了原始列表、中间集合以及最终去重后的列表。

Original list with duplicates: [1, 5, 2, 3, 5, 1, 4, 2, 2, 5]
Set created from list (duplicates gone): {1, 2, 3, 4, 5}
Final list with duplicates removed: [1, 2, 3, 4, 5]

你已成功应用集合知识来解决一个常见的编程问题:从列表中移除重复项。

总结

在本次实验中,你学习了在 Python 中使用集合的基本技能。你从使用不同语法创建集合开始,了解了它们如何固有地保证唯一性。你练习了使用 add()update() 添加元素,以及使用 remove()discard()pop()clear() 移除元素,并注意到了这些方法之间的关键区别。

此外,你还探索了核心的数学集合运算——并集 (|)、交集 (&) 和差集 (-)——这些运算对于数据分析和算法设计至关重要。最后,你将这些知识付诸实践,实现了一种优雅的技术来移除列表中的重复项,这是数据清洗和准备中的常见任务。你现在已经具备了在 Python 程序中有效使用集合的能力。