趋近智
集合存储的是不重复、无序的项。我们来看看可以对它们进行的一些强大操作。这些操作与数学中的集合论类似,并且在根据内容比较和合并数据集合时非常有用。Python 提供了直观的运算符和对应的方法来执行这些操作。
对于接下来的操作,我们将使用两个示例集合:
programmers = {'Alice', 'Bob', 'Charlie', 'David'}
data_scientists = {'Charlie', 'David', 'Eve', 'Frank'}
print(f"Programmers: {programmers}")
print(f"Data Scientists: {data_scientists}")
两个集合的并集会生成一个新集合,其中包含两个原始集合中的所有不重复元素。如果某个元素存在于任一(或两个)集合中,它将在结果并集中只出现一次。
你可以使用竖线运算符 (|) 或 union() 方法来计算并集。
# 使用 | 运算符
all_staff = programmers | data_scientists
print(f"Union (|): {all_staff}")
# 使用 union() 方法
all_staff_method = programmers.union(data_scientists)
print(f"Union (method): {all_staff_method}")
# 注意:并集操作的顺序不影响结果
print(f"Is programmers | data_scientists == data_scientists | programmers? {programmers | data_scientists == data_scientists | programmers}")
两种方法都会得到相同的结果:{'Frank', 'Alice', 'Eve', 'Charlie', 'Bob', 'David'}(请记住,集合是无序的,因此元素的排列顺序可能不同)。这个集合包含了所有是程序员、数据科学家或两者都是的人。
维恩图显示了
programmers和data_scientists集合的并集(所有阴影元素)。
两个集合的交集会生成一个新集合,其中只包含两个原始集合中都存在的元素。
你可以使用与运算符 (&) 或 intersection() 方法来查找交集。
# 使用 & 运算符
common_roles = programmers & data_scientists
print(f"Intersection (&): {common_roles}")
# 使用 intersection() 方法
common_roles_method = programmers.intersection(data_scientists)
print(f"Intersection (method): {common_roles_method}")
两种情况下的结果都是 {'Charlie', 'David'},因为这些是同时列在 programmers 和 data_scientists 集合中的人员。
维恩图显示了
programmers和data_scientists集合的交集(深绿色元素)。
两个集合(比如集合 A 和集合 B)的差集会生成一个新集合,其中包含集合 A 中有而集合 B 中没有的元素。这里要注意顺序:A - B 和 B - A 是不同的。
你可以使用减号运算符 (-) 或 difference() 方法来计算差集。
# 存在于 programmers 但不存在于 data_scientists 的元素
only_programmers = programmers - data_scientists
print(f"Difference (programmers - data_scientists): {only_programmers}")
# 使用 difference() 方法
only_programmers_method = programmers.difference(data_scientists)
print(f"Difference (method): {only_programmers_method}")
# 存在于 data_scientists 但不存在于 programmers 的元素
only_data_scientists = data_scientists - programmers
print(f"Difference (data_scientists - programmers): {only_data_scientists}")
结果如下:
programmers - data_scientists: {'Alice', 'Bob'} (未被列为数据科学家的程序员)。data_scientists - programmers: {'Eve', 'Frank'} (未被列为程序员的数据科学家)。维恩图显示了
programmers - data_scientists的差集(蓝色元素)。
两个集合的对称差集会生成一个新集合,其中包含只存在于任一集合中但不同时存在于两个集合中的元素。这实际上是交集的反面;它包含每个集合中独有的元素。
你可以使用插入符号运算符 (^) 或 symmetric_difference() 方法来计算对称差集。
# 使用 ^ 运算符
exclusive_roles = programmers ^ data_scientists
print(f"Symmetric Difference (^): {exclusive_roles}")
# 使用 symmetric_difference() 方法
exclusive_roles_method = programmers.symmetric_difference(data_scientists)
print(f"Symmetric Difference (method): {exclusive_roles_method}")
两种方法都生成 {'Frank', 'Alice', 'Eve', 'Bob'}。这个集合包含了只是程序员或只是数据科学家的人员,排除了那些身兼二职的人。
维恩图显示了
programmers和data_scientists集合的对称差集(蓝色和浅绿色元素,不包括灰色交集)。
这些集合操作提供了一种简洁高效的方式来比较和处理不重复项的组。它们经常用于数据分析、算法设计以及管理不重复数据集合的多种其他编程工作中。
这部分内容有帮助吗?
© 2026 ApX Machine LearningAI伦理与透明度•