在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)
通過以上示例,可以進行常見的集合運算操作。