Python - 查找多个集合的并集
给定多个集合列表,任务是编写一个Python程序来查找每个集合的并集。
例子:
Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}]
Output : {1, 2, 3, 4, 5, 7, 8, 9}
Explanation : All elements from all sets included. Duplicates removed.
Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}]
Output : {1, 2, 3, 4, 5, 7, 8}
Explanation : All elements from all sets included. Duplicates removed.
方法 #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))
输出:
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]
Multiple set union : {1, 2, 3, 4, 5, 7, 8, 9}
方法 #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))
输出:
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]
Multiple set union : {1, 2, 3, 4, 5, 7, 8, 9}