介绍
欢迎来到关于 Python 集合(Set)的这个实验(Lab)!Python 提供了几种内置的数据类型来组织数据,包括列表(lists)、字典(dictionaries)、元组(tuples)和集合(sets)。
根据 Python 官方文档,集合是一个无序且不包含重复元素的集合。它的主要用途是进行成员资格测试和消除重复条目。
在这个实验中,你将通过一系列动手练习来探索如何创建、操作和有效地使用集合。
初始化集合
在这一步,你将学习在 Python 中创建集合的两种主要方式:使用花括号 {} 和内置的 set() 函数。理解一个关键点非常重要:使用空花括号 {} 创建的是一个空字典 (dictionary),而不是一个空集合 (set)。
注意: 如果你不熟悉使用 WebIDE(类似 VS Code),请先在 这个实验 学习。
首先,从左侧的文件浏览器中打开 step1.py 文件。
现在,将以下代码复制并粘贴到 step1.py 中。这段代码演示了如何创建集合,并强调了创建空集合的特殊情况。
## Create set using curly braces or set() function
s_braces = {1, 2, 3}
print(f"Set with braces: {s_braces}, type: {type(s_braces)}")
s_func = set([1, 2, 3])
print(f"Set with function: {s_func}, type: {type(s_func)}")
## Warning: empty {} creates a dictionary, not a set
s_dict = {}
print(f"Empty braces create a: {type(s_dict)}")
## To create an empty set, you must use set()
s_empty = set()
print(f"To create an empty set use set(): {type(s_empty)}")
保存文件,然后通过在终端执行以下命令来运行它:
python3 step1.py
你应该会看到以下输出,它确认了所创建对象的类型。请注意,{} 的结果是 <class 'dict'>。
Set with braces: {1, 2, 3}, type: <class 'set'>
Set with function: {1, 2, 3}, type: <class 'set'>
Empty braces create a: <class 'dict'>
To create an empty set use set(): <class 'set'>
理解集合特性
在这一步,你将探索集合的核心属性。集合之所以强大,是因为它们会自动强制执行唯一性(uniqueness)并且是无序的(unordered)。这意味着集合会自动删除任何重复的值,并且你不能使用索引来访问它的元素。
打开 step2.py 文件。
将以下代码复制并粘贴到 step2.py 中。代码的第一部分演示了如何处理重复项,第二部分展示了当你尝试对集合进行索引时会发生什么。
## Sets automatically remove duplicates
s_duplicates = {1, 2, 3, 2, 3, 4}
print(f"Original with duplicates: {{1, 2, 3, 2, 3, 4}}")
print(f"Set with duplicates removed: {s_duplicates}")
## Sets are unordered and cannot be indexed
print("\nAttempting to access a set by index...")
try:
s = {1, 2, 3}
s[0]
except TypeError as e:
print(f"Error when indexing: {e}")
现在,从终端运行脚本:
python3 step2.py
输出将是:
Original with duplicates: {1, 2, 3, 2, 3, 4}
Set with duplicates removed: {1, 2, 3, 4}
Attempting to access a set by index...
Error when indexing: 'set' object is not subscriptable
正如你所见,重复的 2 和 3 被自动删除了。尝试访问 s[0] 导致了 TypeError,这证实了集合不支持索引操作。
添加和更新元素
在这一步,你将学习如何向现有集合中添加新元素。Python 提供了两种主要方法:使用 add() 添加单个元素,以及使用 update() 从可迭代对象(如列表或另一个集合)中添加多个元素。
打开 step3.py 文件。
将以下代码复制并粘贴到 step3.py 中。这段代码将首先创建一个集合,然后添加一个元素,最后用多个元素来更新它。
## Start with a set
s = {1, 2, 3}
print(f"Original set: {s}")
## add() method: add a single element
s.add(4)
print(f"After adding 4: {s}")
## update() method: add multiple elements from an iterable
s.update([2, 3, 4, 5, 6]) ## Duplicates like 2, 3, 4 are ignored
print(f"After updating with [2, 3, 4, 5, 6]: {s}")
从终端执行脚本:
python3 step3.py
你的输出应该如下所示。请注意,在使用 update() 时,集合中已存在的任何元素都会被简单地忽略。
Original set: {1, 2, 3}
After adding 4: {1, 2, 3, 4}
After updating with [2, 3, 4, 5, 6]: {1, 2, 3, 4, 5, 6}
移除和丢弃元素
在这一步,你将学习从集合中移除元素的两种方法:remove() 和 discard()。虽然这两种方法都可以移除元素,但当元素不存在时它们的行为不同。remove() 会引发一个 KeyError,如果未处理,这可能会导致你的程序崩溃;而 discard() 则不会执行任何操作并静默继续。
打开 step4.py 文件。
复制并粘贴以下代码,它演示了这两种方法的行为。
## remove() method: raises KeyError if element is not found
s = {1, 2, 3}
print(f"Original set: {s}")
s.remove(3)
print(f"After removing 3: {s}")
## Trying to remove an element that doesn't exist with remove()
try:
s.remove(3)
except KeyError as e:
print(f"Error when removing 3 again: KeyError: {e}")
## discard() method: does not raise an error if element is not found
s = {1, 2, 3}
print(f"\nNew original set: {s}")
s.discard(3)
print(f"After discarding 3: {s}")
s.discard(3) ## No error is raised
print(f"After discarding 3 again (no error): {s}")
从终端运行脚本:
python3 step4.py
输出清晰地展示了区别:
Original set: {1, 2, 3}
After removing 3: {1, 2}
Error when removing 3 again: KeyError: 3
New original set: {1, 2, 3}
After discarding 3: {1, 2}
After discarding 3 again (no error): {1, 2}
在 remove() 和 discard() 之间进行选择,取决于你希望在元素缺失时程序是明确失败(fail explicitly)还是优雅地处理其缺失情况(handle its absence gracefully)。
集合操作
在最后这一步,你将练习最常见的集合运算(Set Operations)。这些运算允许你以强大的方式组合和比较集合。你将同时使用方法语法(例如 s1.union(s2))和运算符语法(例如 s1 | s2)。
- 并集 (
union()或|):创建一个包含所提供集合中所有元素的新集合。 - 交集 (
intersection()或&):返回一个只包含所有集合中共同元素的新集合。 - 差集 (
difference()或-):返回一个包含在第一个集合中但不在第二个集合中的元素的新集合。 - 对称差集 (
symmetric_difference()或^):返回一个包含只存在于其中一个集合中,但不同时存在于两个集合中的元素的新集合。
打开 step5.py 文件。
复制并粘贴以下代码,对两个示例集合执行这四种运算。
s1 = {1, 2, 3}
s2 = {2, 3, 4}
print(f"s1 = {s1}")
print(f"s2 = {s2}\n")
## union() or |
## Returns a new set containing all items from both sets.
print(f"Union (s1 | s2): {s1.union(s2)}")
## intersection() or &
## Returns a new set containing items common to both sets.
s3 = {3, 4, 5}
print(f"Intersection (s1 & s2): {s1.intersection(s2)}")
## difference() or -
## Returns a new set containing items in the first set but not in the second.
print(f"Difference (s1 - s2): {s1.difference(s2)}")
print(f"Difference (s2 - s1): {s2.difference(s1)}")
## symmetric_difference() or ^
## Returns a new set with elements in either set, but not both.
print(f"Symmetric Difference (s1 ^ s2): {s1.symmetric_difference(s2)}")
从终端运行脚本:
python3 step5.py
检查输出以理解每种运算的结果:
s1 = {1, 2, 3}
s2 = {2, 3, 4}
Union (s1 | s2): {1, 2, 3, 4}
Intersection (s1 & s2): {2, 3}
Difference (s1 - s2): {1}
Difference (s2 - s1): {4}
Symmetric Difference (s1 ^ s2): {1, 4}
总结
在这个实验(Lab)中,你学习了 Python 集合(sets)的基础知识。你首先学习了如何使用花括号 {} 和 set() 函数来初始化集合,并注意到了创建空集合时的重要区别。你探索了集合的核心特性:它们是无序的,并且只存储唯一的元素。你练习了通过 add() 和 update() 方法添加元素,以及通过 remove() 和 discard() 方法移除元素来修改集合,并理解了它们之间的关键区别。最后,你执行了基本的集合运算,包括并集 (|)、交集 (&)、差集 (-) 和对称差集 (^)。现在,你已经为在 Python 程序中使用集合来处理唯一项的集合打下了坚实的基础。



