在Python中,可以使用内置的set类型来计算两个集合的交集、并集和差集。这里是一些例子:
# 定义两个集合set1 = {1, 2, 3, 4, 5}set2 = {4, 5, 6, 7, 8}# 计算交集intersection = set1.intersection(set2)print("Intersection:", intersection) # 输出:{4, 5}# 计算并集union = set1.union(set2)print("Union:", union) # 输出:{1, 2, 3, 4, 5, 6, 7, 8}# 计算差集difference = set1.difference(set2)print("Difference:", difference) # 输出:{1, 2, 3}你还可以使用其他方法,比如 & 运算符计算交集,| 运算符计算并集,- 运算符计算差集:
# 计算交集intersection = set1 & set2print("Intersection:", intersection) # 输出:{4, 5}# 计算并集union = set1 | set2print("Union:", union) # 输出:{1, 2, 3, 4, 5, 6, 7, 8}# 计算差集difference = set1 - set2print("Difference:", difference) # 输出:{1, 2, 3} 

