Python中可以使用set数据类型来表示集合,并通过内置方法intersection或&操作符来求两个集合的交集。
例如:
# 定义两个集合set1 = {1, 2, 3, 4}set2 = {3, 4, 5, 6}# 使用intersection方法求交集intersection_set = set1.intersection(set2)print("使用intersection方法求得的交集为:", intersection_set)# 使用&操作符求交集intersection_set = set1 & set2print("使用&操作符求得的交集为:", intersection_set)输出结果为:
使用intersection方法求得的交集为: {3, 4}使用&操作符求得的交集为: {3, 4}在这个例子中,我们首先定义了两个集合set1和set2,然后分别使用intersection方法和&操作符求得了它们的交集。


