在Python中,可以使用set()函数或者集合对象的intersection()方法来计算两个集合的交集。
以下是使用set()函数的示例:
# 定义两个集合set1 = {1, 2, 3, 4}set2 = {3, 4, 5, 6}# 计算交集intersection_set = set1 & set2print(intersection_set) # 输出: {3, 4}以下是使用intersection()方法的示例:
# 定义两个集合set1 = {1, 2, 3, 4}set2 = {3, 4, 5, 6}# 计算交集intersection_set = set1.intersection(set2)print(intersection_set) # 输出: {3, 4}还可以使用intersection()方法同时计算多个集合的交集:
# 定义三个集合set1 = {1, 2, 3, 4}set2 = {3, 4, 5, 6}set3 = {3, 4, 7, 8}# 计算交集intersection_set = set1.intersection(set2, set3)print(intersection_set) # 输出: {3, 4} 

