本文演示了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]))
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
评论前必须登录!
注册