Python Set intersection() 函数用法

2023-09-17 22:24:30

set.intersection() 方法返回一个新集合,其中包含给定集合中常见的元素。

语法:

set.intersection(*other_sets)

参数:

other_sets:可选。逗号分隔一个或多个集合。如果未传递任何参数,则返回集合的浅表副本。

返回值:

所有集合中具有共同元素的集合。

下面的示例演示 set.intersection() 方法。

nums = {1, 2, 3, 4, 5 }
oddNums = {1, 3, 5, 7, 9}
commonNums = nums.intersection(oddNums)
print("Common elements in nums and oddNums are: ", commonNums)
numscopy = nums.intersection() # returns shallow copy if no argument passed
print("Shallow copy: ", numscopy)

输出:

Common elements in nums and oddNums are:  {1, 3, 5}
Shallow copy: {1, 2, 3, 4, 5 }

set.intersection()方法也可以处理多个集合。

nums = {1, 2, 3, 4, 5}
oddNums = {1, 3, 5, 6, 7, 9}
primeNums = {2, 3, 5, 7}
commonNums = nums.intersection(oddNums, primeNums)
print("Common elements: ", commonNums)

输出:

Common elements: {3, 5}

&运算符还可用于查找集合的交集。

nums = {1,2,3,4,5,6,7,8,9,10}
oddNums = {1,3,5,6,7,9}
primeNums = {2,3,5,7}
commonNums = Nums & oddNums & primeNums
print("Common elements: ", commonNums)

输出:

Common elements: {3, 5}

如果未找到公共元素,则返回一个空集。

nums = {10, 20, 30, 40}
oddNums = {1, 3, 5, 6, 7, 9}
commonNums = nums & oddNums
print("Common elements: ", commonNums)
commonNums = nums.intersection(oddNums)
print("Common elements: ", commonNums)

输出:

Common elements: set()