温馨提示×

python set运算的交集如何求

小樊
82
2024-08-27 11:16:49
栏目: 编程语言

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 & set2
print("使用&操作符求得的交集为:", intersection_set)

输出结果为:

使用intersection方法求得的交集为: {3, 4}
使用&操作符求得的交集为: {3, 4}

在这个例子中,我们首先定义了两个集合set1和set2,然后分别使用intersection方法和&操作符求得了它们的交集。

0