📜  Python集合操作(并、交、差和对称差)

📅  最后修改于: 2022-05-13 01:54:45.687000             🧑  作者: Mango

Python集合操作(并、交、差和对称差)

本文演示了对Python集的不同操作。
例子:

Input :
A = {0, 2, 4, 6, 8}
B = {1, 2, 3, 4, 5}

Output :
 Union : [0, 1, 2, 3, 4, 5, 6, 8]
 Intersection : [2, 4]
 Difference : [8, 0, 6]
 Symmetric difference : [0, 1, 3, 5, 6, 8]

在Python中,以下快速操作数可用于不同的操作。

# Program to perform different set operations
# as we do in  mathematics
  
# sets are define
A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};
  
# union
print("Union :", A | B)
  
# intersection
print("Intersection :", A & B)
  
# difference
print("Difference :", A - B)
  
# symmetric difference
print("Symmetric difference :", A ^ B)

输出:

('Union :', set([0, 1, 2, 3, 4, 5, 6, 8]))
('Intersection :', set([2, 4]))
('Difference :', set([8, 0, 6]))
('Symmetric difference :', set([0, 1, 3, 5, 6, 8]))