Python中集合的交、并、补运算可通过以下关键字或方法实现:
一、交集(Intersection)
-
方法 :
intersection()
或&
运算符set1 = {'卢俊义', '花荣', '吴用'} set2 = {'公孙胜', '秦明', '卢俊义'} res = set1.intersection(set2) # 或 res = set1 & set2 print(res) # {'卢俊义'}
-
特点 :返回两个集合中共同的元素。
二、并集(Union)
-
方法 :
union()
或|
运算符res = set1.union(set2) # 或 res = set1 | set2 print(res) # {'卢俊义', '花荣', '吴用', '公孙胜', '秦明'}
-
特点 :返回两个集合中所有不重复的元素。
三、差集(Difference)
-
方法 :
difference()
或-
运算符res = set1.difference(set2) # 或 res = set1 - set2 print(res) # {'花荣', '吴用'}
-
特点 :返回在第一个集合中但不在第二个集合中的元素。
四、对称差集(Symmetric Difference)
-
方法 :
symmetric_difference()
或^
运算符res = set1.symmetric_difference(set2) # 或 res = set1 ^ set2 print(res) # {'花荣', '吴用', '公孙胜', '秦明'}
-
特点 :返回两个集合中不相同的元素(即交集的补集)。
五、子集判断(Subset)
-
方法 :
issubset()
res = set1.issubset(set2) # 判断set1是否为set2的子集 print(res) # True
-
特点 :返回布尔值,表示一个集合是否完全包含于另一个集合中。
注意 :以上操作均基于集合类型(set
),若操作列表需先转换为集合。例如:
a = [1, 2, 3]
b = [2, 4]
set_a = set(a)
set_b = set(b)
res = set_a.intersection(set_b) # {'2'}