温馨提示×

在Python中如何使用set方法求交集

小樊
82
2024-09-16 11:45:19
栏目: 编程语言

在Python中,可以使用内置的集合(set)类型来求两个集合的交集。具体来说,可以使用 intersection 方法或者 & 运算符来实现这一目标。下面是两种方法的示例:

# 使用 intersection 方法
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection_set = set1.intersection(set2)
print(intersection_set)  # 输出: {3, 4}

# 使用 & 运算符
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection_set = set1 & set2
print(intersection_set)  # 输出: {3, 4}

在这两个示例中,我们首先定义了两个集合 set1set2,然后使用 intersection 方法或 & 运算符来求它们的交集。最后,我们打印出交集,得到结果 {3, 4}

0