Python Set intersection

Python Set intersection()

转自:https://www.programiz.com/python-programming/methods/set/intersection

The intersection() method returns a new set with elements that are common to all sets.

The intersection of two or more sets is the set of elements which are common to all sets. For example:

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}

Intersection of Three Sets


The syntax of intersection() in Python is:

A.intersection(*other_sets)

intersection() Parameters

The intersection() allows arbitrary number of arguments (sets).

Note: * is not part of the syntax. It is used to indicate that the method allows arbitrary number of arguments.


Return Value from Intersection()

The intersection() method returns the intersection of set A with all the sets (passed as argument).

 

If argument is not passed to intersection(), it returns a shallow copy the set (A).


Example 1: How intersection() works?

 

1

2

3

4

5

6

7

8

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

Run

Powered by DataCamp

When you run the program, the output will be:

{2, 5}
{2}
{2, 3}
{2}

More Examples

 

1

2

3

4

5

6

7

8

9

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

Run

Powered by DataCamp

When you run the program, the output will be:

{100}
{200}
{300}
set()

You can also find the intersection of sets using & operator


Example 3: Set Intersection Using & operator

 

1

2

3

4

5

6

7

8

9

10

11

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)

Run

Powered by DataCamp

When you run the program, the output will be:

{7}
{100}
set()
set()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值