Intersection()函数Python
Python intersection()函数返回一个新集合,其中包含所有集合共有的元素
两个给定集合的交集是最大集合,它包含两个集合共有的所有元素。两个给定集合 A 和 B 的交集是由 A 和 B 共有的所有元素组成的集合。
交集的例子:
Input: Let set A = {2, 4, 5, 6}
and set B = {4, 6, 7, 8}
Output: {4,6}
Explanation: Taking the common elements in both the sets, we get {4,6} as the intersection of both the sets.
Python交集() 语法:
set1.intersection(set2, set3, set4….)
In parameters, any number of sets can be given
Python交集()返回值:
The intersection() function returns a set, which has the intersection of all sets(set1, set2, set3…) with set1. It returns a copy of set1 only if no parameter is passed.
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()