Set在Python能做集合运算吗

   2024-10-02 4630
核心提示:是的,Set在Python中可以进行集合运算。可以使用以下常见的集合运算:并集:使用union()方法或|运算符交集:使用intersecti

是的,Set在Python中可以进行集合运算。可以使用以下常见的集合运算:

并集:使用union()方法或|运算符交集:使用intersection()方法或&运算符差集:使用difference()方法或-运算符对称差集:使用symmetric_difference()方法或^运算符

例如:

set1 = {1, 2, 3}set2 = {2, 3, 4}# 并集union_set = set1.union(set2)print(union_set)  # 输出 {1, 2, 3, 4}# 交集intersection_set = set1.intersection(set2)print(intersection_set)  # 输出 {2, 3}# 差集difference_set = set1.difference(set2)print(difference_set)  # 输出 {1}# 对称差集symmetric_difference_set = set1.symmetric_difference(set2)print(symmetric_difference_set)  # 输出 {1, 4}

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号