📜  Intersection()函数Python

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

Intersection()函数Python

Python intersection()函数返回一个新集合,其中包含所有集合共有的元素

两个给定集合的交集是最大集合,它包含两个集合共有的所有元素。两个给定集合 A 和 B 的交集是由 A 和 B 共有的所有元素组成的集合。

交集的例子:

Python交集() 语法:

Python交集()返回值:

Python交集() 示例

示例 1:set intersection() 的工作

Python3
# Python3 program for intersection() function
set1 = {2, 4, 5, 6}
set2 = {4, 6, 7, 8}
set3 = {4, 6, 8}
 
# union of two sets
print("set1 intersection set2 : ",
      set1.intersection(set2))
 
# union of three sets
print("set1 intersection set2 intersection set3 :",
      set1.intersection(set2, set3))


Python3
# Python3 program for intersection() function
set1 = {2, 4, 5, 6}
set2 = {4, 6, 7, 8}
set3 = {1, 0, 12}
 
print(set1 & set2)
print(set1 & set3)
 
print(set1 & set2 & set3)


Python3
# Python3 program for intersection() function
set1 = {2, 4, 5, 6}
set2 = {4, 6, 7, 8}
set3 = {1, 0, 12}
 
print(set1.symmetric_difference(set2))
print(set1.symmetric_difference(set3))
print(set2.symmetric_difference(set3))


Python3
set1 = {}
set2 = {}
 
# union of two sets
print("set1 intersection set2 : ",
      set(set1).intersection(set(set2)))


输出:

set1 intersection set2 :  {4, 6}
set1 intersection set2 intersection set3 : {4, 6}

示例 2: Python集合交集运算符(&)

我们也可以使用 &运算符获得交集。

Python3

# Python3 program for intersection() function
set1 = {2, 4, 5, 6}
set2 = {4, 6, 7, 8}
set3 = {1, 0, 12}
 
print(set1 & set2)
print(set1 & set3)
 
print(set1 & set2 & set3)

输出:

{4, 6}
set()
set()

示例 3: Python设置对面的交集

symmetric_difference() 与 set.intersection() 方法相反。

Python3

# Python3 program for intersection() function
set1 = {2, 4, 5, 6}
set2 = {4, 6, 7, 8}
set3 = {1, 0, 12}
 
print(set1.symmetric_difference(set2))
print(set1.symmetric_difference(set3))
print(set2.symmetric_difference(set3))

输出:

{2, 5, 7, 8}
{0, 1, 2, 4, 5, 6, 12}
{0, 1, 4, 6, 7, 8, 12}

示例 4: Python设置交集为空

Python3

set1 = {}
set2 = {}
 
# union of two sets
print("set1 intersection set2 : ",
      set(set1).intersection(set(set2)))

输出:

set1 intersection set2 :  set()