📜  Python - 查找多个集合的并集

📅  最后修改于: 2022-05-13 01:54:47.265000             🧑  作者: Mango

Python - 查找多个集合的并集

给定多个集合列表,任务是编写一个Python程序来查找每个集合的并集。

例子:

方法 #1:使用union() + *运算符

在这里,我们使用 union() 来执行获取并集的任务,并且使用 *运算符来执行将所有集合打包在一起的任务。

Python3
# Python3 code to demonstrate working of
# Union multiple sets
# Using union() + * operator
  
# initializing list
test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# * operator packs sets for union
res = set().union(*test_list)
  
# printing result
print("Multiple set union : " + str(res))


Python3
# Python3 code to demonstrate working of
# Union multiple sets
# Using chain.from_iterable() + * operator
from itertools import chain
  
# initializing list
test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# * operator packs sets for union
res = set(chain(*test_list))
  
# printing result
print("Multiple set union : " + str(res))


输出:

方法 #2:使用chain.from_iterable() + *运算符

在这里,我们执行联合任务,这反过来又使用 from_iterable() 进行展平。

蟒蛇3

# Python3 code to demonstrate working of
# Union multiple sets
# Using chain.from_iterable() + * operator
from itertools import chain
  
# initializing list
test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# * operator packs sets for union
res = set(chain(*test_list))
  
# printing result
print("Multiple set union : " + str(res))

输出: