Python - 多组交集
在本文给出的集合列表中,任务是编写一个Python程序来执行它们的交集。
例子:
Input : test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]
Output : {3, 5}
Explanation : 3 and 5 is present in all the sets.
Input : test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 4}]
Output : {5}
Explanation : 5 is present in all the sets.
方法#1:使用intersection() + *运算符
在这里,我们使用intersection() 执行获取交集的任务,*运算符用于将所有集合打包在一起。
Python3
# Python3 code to demonstrate working of
# Multiple Sets Intersection
# Using intersection() + * operator
# initializing list
test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]
# printing original list
print("The original list is : " + str(test_list))
# getting all sets intersection using intersection()
res = set.intersection(*test_list)
# printing result
print("Intersected Sets : " + str(res))
Python3
# Python3 code to demonstrate working of
# Multiple Sets Intersection
# Using reduce() + and_ operator
from operator import and_
from functools import reduce
# initializing list
test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]
# printing original list
print("The original list is : " + str(test_list))
# getting all sets intersection using and_ operator
res = set(reduce(and_, test_list))
# printing result
print("Intersected Sets : " + str(res))
输出:
The original list is : [{3, 5, 6, 7}, {1, 2, 3, 5}, {8, 3, 5, 7}, {8, 3, 4, 5}]
Intersected Sets : {3, 5}
方法 #2:使用reduce() + and_运算符
在这里,我们使用 and_运算符执行交集任务,reduce() 执行将所有集合打包在一起以进行所需操作的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Multiple Sets Intersection
# Using reduce() + and_ operator
from operator import and_
from functools import reduce
# initializing list
test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}]
# printing original list
print("The original list is : " + str(test_list))
# getting all sets intersection using and_ operator
res = set(reduce(and_, test_list))
# printing result
print("Intersected Sets : " + str(res))
输出:
The original list is : [{3, 5, 6, 7}, {1, 2, 3, 5}, {8, 3, 5, 7}, {8, 3, 4, 5}]
Intersected Sets : {3, 5}