📅  最后修改于: 2020-09-20 13:32:53             🧑  作者: Mango
两个或更多集合的交集是所有集合共同的元素集合。例如:
A = {1, 2, 3, 4}
B = {2, 3, 4, 9}
C = {2, 4, 9 10}
Then,
A∩B = B∩A ={2, 3, 4}
A∩C = C∩A ={2, 4}
B∩C = C∩B ={2, 4, 9}
A∩B∩C = {2, 4}
Python中intersection()
的语法为:
A.intersection(*other_sets)
intersection()
允许任意数量的参数(集合)。
注意: *
不是语法的一部分。用于指示该方法允许任意数量的参数。
intersection()
方法返回集合A
与所有集合的交集(作为参数传递)。
如果未将参数传递给intersection()
,则它返回集合( A
)的浅表副本。
A = {2, 3, 5, 4}
B = {2, 5, 100}
C = {2, 3, 8, 9, 10}
print(B.intersection(A))
print(B.intersection(C))
print(A.intersection(C))
print(C.intersection(A, B))
输出
{2, 5}
{2}
{2, 3}
{2}
A = {100, 7, 8}
B = {200, 4, 5}
C = {300, 2, 3}
D = {100, 200, 300}
print(A.intersection(D))
print(B.intersection(D))
print(C.intersection(D))
print(A.intersection(B, C, D))
输出
{100}
{200}
{300}
set()
您还可以使用&
运算符找到集合的交集。
A = {100, 7, 8}
B = {200, 4, 5}
C = {300, 2, 3, 7}
D = {100, 200, 300}
print(A & C)
print(A & D)
print(A & C & D)
print(A & B & C & D)
输出
{7}
{100}
set()
set()