📜  Python - 多组交集

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

Python - 多组交集

在本文给出的集合列表中,任务是编写一个Python程序来执行它们的交集。

例子:

方法#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))


输出:

方法 #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))

输出: