阅读量:92
是的,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}