在Python中,可以使用set类型进行集合运算。常见的集合运算包括并集、交集、差集和对称差集等操作。
以下是一些常见的集合运算示例:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 使用"|"操作符
union_set = set1 | set2
print(union_set)
# 使用union()方法
union_set = set1.union(set2)
print(union_set)
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 使用"&"操作符
intersection_set = set1 & set2
print(intersection_set)
# 使用intersection()方法
intersection_set = set1.intersection(set2)
print(intersection_set)
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 使用"-"操作符
difference_set = set1 - set2
print(difference_set)
# 使用difference()方法
difference_set = set1.difference(set2)
print(difference_set)
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 使用"^"操作符
symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set)
# 使用symmetric_difference()方法
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set)
通过以上示例,可以进行常见的集合运算操作。