在 Python 中,set
集合对象具有 intersection()
方法,该方法用于计算两个集合的交集,也就是找到两个集合中共同存在的元素并返回一个新的集合。
# 创建两个集合
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
# 使用 intersection() 方法计算两个集合的交集
intersection_set = set1.intersection(set2)
# 输出交集结果
print(intersection_set) # 输出结果为 {3, 4, 5}
在上面的示例中,我们首先创建了两个集合 set1
和 set2
,然后使用 intersection()
方法来计算它们的交集,并将结果存储在 intersection_set
变量中。最后,我们输出交集的结果,它包含了两个集合中共同存在的元素 {3, 4, 5}
。
intersection()
方法返回一个新的集合,包含了两个集合的共同元素。原始集合 set1
和 set2
不受影响。也可以使用 &
运算符来执行交集操作,例如 set1 & set2
。