在Python中,可以使用set類(lèi)型進(jìn)行集合運(yùn)算。常見(jiàn)的集合運(yùn)算包括并集、交集、差集和對(duì)稱(chēng)差集等操作。
以下是一些常見(jiàn)的集合運(yùn)算示例:
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)
通過(guò)以上示例,可以進(jìn)行常見(jiàn)的集合運(yùn)算操作。