是的,在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()
)等。