2018年4月13日 星期五

Python - 在Python上使用交集、聯集、差集 - How to use intersection,difference,union in Python

Information:

System version : Windows 10 64-bit
Python version : Python 3.6.0 :: Anaconda 4.3.1 (64-bit)

Code:

A = set([1,2,3,4])
B = set([2,3,5])

# 交集
set_list = [A,B]
intersection_A_B = set.intersection(*set_list)
# 差集
difference_A_B = A.difference(B)
difference_B_A = B.difference(A)
# 聯集
union_A_B = A.union(B)

print('交集')
print('intersection_A_B :',intersection_A_B)
print('差集')
print('difference_A_B :',difference_A_B)
print('difference_B_A :',difference_B_A)
print('聯集')
print('union_A_B :',union_A_B)

Result:

交集
intersection_A_B : {2, 3}
差集
difference_A_B : {1, 4}
difference_B_A : {5}
聯集
union_A_B : {1, 2, 3, 4, 5}

沒有留言:

張貼留言