Python Set联合

时间:2020-02-23 14:43:18  来源:igfitidea点击:

在集合论中,集合与集合的并集是集合与集合中所有元素的集合。

Python 集合的联合

Python set类提供union()函数来获取集合集合的并集。
结果是一个新集合,其中包含集合集合中的所有元素。

让我们来看一些Python set union()函数的示例。

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

print(set1.union(set2))
print(set2.union(set3))
print(set3.union(set1))

输出:

{1, 2, 3, 4, 5, 6}
{2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 6, 7}

多集的并集

我们可以通过两种方式创建多个集合的并集。

  • 通过传递多个集合作为union()函数的参数。

  • 由于union()返回一个新集合,因此我们可以创建一个union()函数调用链。

下面的代码片段显示了以上两种方式的实现。

print(set1.union(set2, set3))
#  OR
print(set1.union(set2).union(set3))

输出:

{1, 2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 5, 6, 7}