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

本文演示了在上的不同操作 Python集合 . 例如:

null
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]))
© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享