用python求集合的交并差和补运算
时间: 2024-03-14 09:45:52 浏览: 25
可以使用Python内置的集合操作函数来求解集合的交并差和补运算。具体代码如下:
```python
# 定义两个集合
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 求并集
union_set = set1.union(set2)
print("并集:", union_set)
# 求交集
intersection_set = set1.intersection(set2)
print("交集:", intersection_set)
# 求差集
diff_set1 = set1.difference(set2)
print("集合1相对于集合2的差集:", diff_set1)
diff_set2 = set2.difference(set1)
print("集合2相对于集合1的差集:", diff_set2)
# 求对称差集
symmetric_diff_set = set1.symmetric_difference(set2)
print("对称差集:", symmetric_diff_set)
# 求补集
complement_set = set1.difference(set2)
print("集合2相对于集合1的补集:", complement_set)
```
运行结果如下:
```
并集: {1, 2, 3, 4, 5, 6, 7, 8}
交集: {4, 5}
集合1相对于集合2的差集: {1, 2, 3}
集合2相对于集合1的差集: {8, 6, 7}
对称差集: {1, 2, 3, 6, 7, 8}
集合2相对于集合1的补集: {1, 2, 3}
```