Python 集合并集

Python 的 union 函数将原始集合和指定的集合中的所有元素合并,其语法如下:

set.union(set1, set2,…,setN)

Python 集合并集示例

在此示例中,我们声明了两个集合,然后使用 union 方法将它们合并。

x = {'a', 'b', 'c', 'd'}
y = {'e', 'f', 'g', 'h'}
 
print('Items in x = ', x)
print('Items in y = ', y)
 
z = x.union(y)
 
print('Items in z = ', z)
Items in x =  {'c', 'd', 'b', 'a'}
Items in y =  {'f', 'h', 'e', 'g'}
Items in z =  {'f', 'h', 'd', 'g', 'c', 'b', 'a', 'e'}

集合不允许包含重复值。因此,使用 union 方法合并两个集合会删除重复值。如果您观察输出,a 和 c 只返回了一次(尽管它们同时存在于 x 和 y 中)。

提示:请参考 Programming 中的 Python 集合

x = {'a', 'b', 'c', 'd'}
y = {'a', 'f', 'g', 'c', 'h', 'j', 'k'}
 
print('x = ', x)
print('y = ', y)
 
z = x.union(y)
 
print('z = ', z)
x =  {'b', 'a', 'c', 'd'}
y =  {'k', 'j', 'g', 'a', 'c', 'h', 'f'}
z =  {'b', 'k', 'a', 'd', 'j', 'g', 'c', 'h', 'f'}

集合并集函数 示例 2

我将使用三个集合与 union 函数。此示例合并了所有三个集合。它首先合并 x 中的元素,然后合并 y 和 z 中的元素。

x = {'a', 'b' }
y = {'e', 'f', 'g', 'h'}
z = {'apple', 'cherry', 'kiwi'}
 
print('Items in x = ', x)
print('Items in y = ', y)
print('Items in z = ', z)
 
new = x.union(y, z)
 
print('Items in new = ', new)
Items in x =  {'a', 'b'}
Items in y =  {'h', 'g', 'e', 'f'}
Items in z =  {'kiwi', 'apple', 'cherry'}
Items in new =  {'kiwi', 'g', 'h', 'apple', 'e', 'a', 'f', 'b', 'cherry'}

此示例演示了如何合并数字和字符串。

x = {'a', 'b' }
y = {10, 20, 30, 40}
 
print('Items in x = ', x)
print('Items in y = ', y)
 
z = x.union(y)
 
print('Items in z = ', z)

合并数字和字符串输出

Items in x =  {'b', 'a'}
Items in y =  {40, 10, 20, 30}
Items in z =  {20, 'b', 40, 10, 30, 'a'}

在这里,我们声明了一个数字集合、一个字符串集合和一个混合集合。接下来,我们使用该方法将它们全部合并并返回一个新的集合。

x = {'a', 'b' }
y = {10, 20, 30, 40}
z = {120, 'cherry', 90, 'kiwi'}
 
print('Set Items in x = ', x)
print('Set Items in y = ', y)
print('Set Items in z = ', z)
 
new_set = x.union(y, z)
 
print('Set Items in new = ', new_set)
set union Function Example