当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Set intersection()用法及代码示例


设置 intersection() 方法

intersection() 方法用于获取在给定集合中共有/存在的所有元素的列表。

用法:

    set1.intersection(set1, set2, set3, ...)

参数:

  • set1– 表示要与该集合进行比较的集合。
  • set2, set3, ...– 这些是可选的集合,我们可以提供多个集合进行比较。

返回值:

这个方法的返回类型是<class 'set'>,它返回存在于所有集合中的元素的集合。

范例1:

# Python Set intersection() Method with Example

# declaring the sets
cars_1 = {"Porsche", "Audi", "Lexus"}
cars_2 = {"Porsche", "Mazda", "Lincoln"}

# intersection() method call
x = cars_1.intersection(cars_2)

# printing the sets
print("cars_1:", cars_1)
print("cars_2:", cars_2)
print("x:", x)

输出

cars_1:{'Porsche', 'Audi', 'Lexus'}
cars_2:{'Porsche', 'Lincoln', 'Mazda'}
x:{'Porsche'}

范例2:

# Python Set intersection() Method with Example

# declaring the sets
x = {"ABC", "PQR", "XYZ"}
y = {"ABC", "PQR", "XYZ"}
z = {"DEF", "MNO", "ABC"}

# printing the results
print("x:", x)
print("y:", y)
print("z:", z)

# printing the common elements
print("x.intersection(y,z):", x.intersection(y,z))
print("y.intersection(x,z):", y.intersection(x,z))
print("x.intersection(z,y):", x.intersection(z,y))
print("y.intersection(z,x):", y.intersection(z,x))
print("z.intersection(x,y):", z.intersection(x,y))

输出

x:{'PQR', 'ABC', 'XYZ'}
y:{'PQR', 'ABC', 'XYZ'}
z:{'DEF', 'ABC', 'MNO'}
x.intersection(y,z): {'ABC'}
y.intersection(x,z): {'ABC'}
x.intersection(z,y): {'ABC'}
y.intersection(z,x): {'ABC'}
z.intersection(x,y): {'ABC'}


相关用法


注:本文由纯净天空筛选整理自 Python Set intersection() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。