python set交集_Python Set交集()方法与示例

python set交集

设置交集()方法 (Set intersection() Method)

intersection() method is used to get the list of all elements which are commons/exist in given sets.

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

Syntax:

句法:

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

Parameter(s):

参数:

  • set1 – It represents the set to be compared with this set.

    set1 –代表要与此集合进行比较的集合。

  • set2, set3, ... – These are optional sets, we can provide multiple sets to be compared.

    set2,set3,... –这些是可选集,我们可以提供多个要比较的集。

Return value:

返回值:

The return type of this method is <class 'set'>, it returns the set of the elements which are exist in all sets.

此方法的返回类型为<class'set'> ,它返回所有集合中都存在的元素的集合。

Example 1:

范例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)

Output

输出量

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

Example 2:

范例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))

Output

输出量

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'}


翻译自: https://www.includehelp.com/python/set-intersection-method-with-example.aspx

python set交集

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值