阅读量:2
是的,在Python中,set可以进行集合运算。集合运算主要包括并集(union)、交集(intersection)、差集(difference)和对称差集(symmetric_difference)。以下是如何使用这些运算的示例:
# 定义两个集合
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 并集
union_set = set1.union(set2)
print("并集:", union_set) # 输出: {1, 2, 3, 4, 5, 6, 7, 8}
# 交集
intersection_set = set1.intersection(set2)
print("交集:", intersection_set) # 输出: {4, 5}
# 差集
difference_set = set1.difference(set2)
print("差集:", difference_set) # 输出: {1, 2, 3}
# 对称差集
symmetric_difference_set = set1.symmetric_difference(set2)
print("对称差集:", symmetric_difference_set) # 输出: {1, 2, 3, 6, 7, 8}
此外,set还支持其他操作,如检查元素是否存在(in或not in)、遍历元素、返回集合大小(len())等。
以上就是关于“python中set能进行集合运算吗”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm