python

python set运算如何实现集合的交集

小樊
82
2024-08-27 10:52:09
栏目: 编程语言

在Python中,可以使用set()函数或者集合对象的intersection()方法来计算两个集合的交集。

以下是使用set()函数的示例:

# 定义两个集合
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# 计算交集
intersection_set = set1 & set2
print(intersection_set)  # 输出: {3, 4}

以下是使用intersection()方法的示例:

# 定义两个集合
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# 计算交集
intersection_set = set1.intersection(set2)
print(intersection_set)  # 输出: {3, 4}

还可以使用intersection()方法同时计算多个集合的交集:

# 定义三个集合
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set3 = {3, 4, 7, 8}

# 计算交集
intersection_set = set1.intersection(set2, set3)
print(intersection_set)  # 输出: {3, 4}

0
看了该问题的人还看了