了解字符串集合
在这一步中,你将了解 Python 中的字符串集合。集合是一个无序的唯一元素集合。这意味着集合不能包含重复的值。集合对于执行数学集合操作(如并集、交集和差集)非常有用。在这个实验中,我们将专注于包含字符串的集合。
首先,让我们创建一个简单的字符串集合。在 LabEx 环境中打开 VS Code 编辑器。在 ~/project
目录下创建一个名为 string_sets.py
的新文件。
## ~/project/string_sets.py
string_set = {"apple", "banana", "cherry"}
print(string_set)
保存文件。现在,在终端中使用 python
命令运行脚本:
python ~/project/string_sets.py
你应该会看到以下输出(元素的顺序可能会有所不同,因为集合是无序的):
{'cherry', 'banana', 'apple'}
现在,让我们向集合中添加一个重复元素,看看会发生什么:
## ~/project/string_sets.py
string_set = {"apple", "banana", "cherry", "apple"}
print(string_set)
保存文件并再次运行:
python ~/project/string_sets.py
输出将是:
{'cherry', 'banana', 'apple'}
注意,重复的 "apple" 被自动移除了。集合只存储唯一的元素。
接下来,让我们探索一些常见的集合操作。我们将创建两个集合,并执行并集和交集操作。
## ~/project/string_sets.py
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "date", "fig"}
## Union of two sets
union_set = set1.union(set2)
print("Union:", union_set)
## Intersection of two sets
intersection_set = set1.intersection(set2)
print("Intersection:", intersection_set)
保存文件并运行:
python ~/project/string_sets.py
输出将是:
Union: {'cherry', 'banana', 'date', 'apple', 'fig'}
Intersection: {'banana'}
两个集合的并集包含了两个集合中的所有唯一元素。交集只包含两个集合中共同的元素。