温馨提示×

set() python如何进行交集操作

小樊
98
2024-07-29 14:22:10
栏目: 编程语言

在Python中,可以使用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}

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

以上代码将两个集合set1和set2的交集存储在intersection_set中,并输出结果。

0