Python中的集合函数:并、交、差和对称差的计算
发布时间:2023-07-01 05:45:35
Python中的集合函数包括并集、交集、差集和对称差集等。这些函数可以用于操作集合并返回操作结果。
1. 并集(Union):
并集操作可以将两个集合中的所有元素合并到一个新的集合中。在Python中,可以使用union()函数或|运算符进行并集操作。例如:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
# 或者可以使用 | 运算符
# result = set1 | set2
print(result) # 输出: {1, 2, 3, 4, 5}
2. 交集(Intersection):
交集操作可以返回两个集合中共有的元素。在Python中,可以使用intersection()函数或&运算符进行交集操作。例如:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.intersection(set2)
# 或者可以使用 & 运算符
# result = set1 & set2
print(result) # 输出: {3}
3. 差集(Difference):
差集操作可以返回在 个集合中但不在第二个集合中的元素。在Python中,可以使用difference()函数或-运算符进行差集操作。例如:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.difference(set2)
# 或者可以使用 - 运算符
# result = set1 - set2
print(result) # 输出: {1, 2}
4. 对称差集(Symmetric Difference):
对称差集操作可以返回两个集合中互相没有的元素。换句话说,对称差集操作会返回两个集合的并集去掉交集部分的元素。在Python中,可以使用symmetric_difference()函数或^运算符进行对称差集操作。例如:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.symmetric_difference(set2)
# 或者可以使用 ^ 运算符
# result = set1 ^ set2
print(result) # 输出: {1, 2, 4, 5}
需要注意的是,这些集合操作函数和运算符都是返回新的集合,而不会修改原来的集合。另外,集合操作函数和运算符也适用于其他可迭代对象,如列表和元组等。
综上所述,Python中的集合函数提供了便捷的方法来进行集合的并、交、差和对称差的计算,方便处理集合运算问题。
