python

如何用set()函数实现交集、并集操作

小樊
84
2024-08-29 15:17:00
栏目: 编程语言

在Python中,可以使用内置的set()函数和一些其他方法来实现交集(intersection)和并集(union)操作。

首先,创建两个集合:

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

接下来,我们将使用set()函数和其他方法来计算这两个集合的交集和并集。

  1. 交集(Intersection): 要计算两个集合的交集,可以使用&运算符或者intersection()方法。

使用&运算符:

intersection_set = set1 & set2
print("Intersection using '&' operator:", intersection_set)

使用intersection()方法:

intersection_set = set1.intersection(set2)
print("Intersection using 'intersection()' method:", intersection_set)
  1. 并集(Union): 要计算两个集合的并集,可以使用|运算符或者union()方法。

使用|运算符:

union_set = set1 | set2
print("Union using '|' operator:", union_set)

使用union()方法:

union_set = set1.union(set2)
print("Union using 'union()' method:", union_set)

上述代码将分别输出交集和并集的结果。

0
看了该问题的人还看了