How to find the intersection, union, difference and symmetric difference set of the set in Python.

Time:2020-11-23

In fact, intersection, union, difference and symmetric difference sets are also special operations of sets.

A & B: the common element of two sets of intersection table, equivalent to A. intersection (b)

A | B: Union table all elements of two sets, equivalent to A. Union (b)

A-B: elements of difference table belonging to a but not to B, equivalent to A. difference (b)

A ^ B: the non common elements of two sets, equivalent to a.symmetric_ difference(b)

The code is as follows:

Find the intersection of sets

#Define two sets
 x = set("abc")
 y = set("cdef")
 #Set intersection
 result = x & y
 print(result)
 #Use intersection () to find the intersection
 result = x.intersection(y)
 print(result)

Operation results:

 

Find the union of sets

x = set("abc")
 y = set("cdef")
 #Use "|" for union
 result = x | y
 print(result)
 #Union() method for union
 result = x.union(y)
 print(result)

Operation results:

 

Find the difference set of the set

x = set("abc")
 y = set("cdef")
 #Use "-" to find the difference set (only belongs to x, not to y)
 result = x - y
 print(result)
 #Use difference() to find the difference set
 result = x.difference(y)
 print(result)

Operation results:

 

 

Find the symmetric difference set of a set

x = set("abc")
y = set("cdef")
#Use ^ to find symmetric difference sets (two sets are not common elements)
result = x ^ y
print(result)
#Using symmetric_ Difference() for symmetric difference set
result = x.symmetric_difference(y)
print(result)

Operation results:

 

Recommended Today

Interviewer: young man, what do you think of the principle of distributed system

1 Concept 1.1 model 1.2 copies 1.3 indicators for measuring distributed systems 2. Principle of distributed system 2.1 data distribution 2.2 basic copy agreement 2.3 lease mechanism 2.4 quorum mechanism 2.5 log technology 2.6 two phase submission protocol 2.7 MVCC 2.8 Paxos protocol 2.9 CAP 1 Concept 1.1 model node In a specific project, a […]