python的集合运算
时间: 2023-12-11 14:33:21 浏览: 114
Python3.5集合及其常见运算实例详解
以下是Python中集合运算的例子:
1. 创建集合
```python
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
```
2. 并集运算
```python
set3 = set1 | set2
print(set3) # 输出:{1, 2, 3, 4, 5, 6, 7, 8}
```
3. 交集运算
```python
set4 = set1 & set2
print(set4) # 输出:{4, 5}
```
4. 差集运算
```python
set5 = set1 - set2
print(set5) # 输出:{1, 2, 3}
```
5. 对称差集运算
```python
set6 = set1 ^ set2
print(set6) # 输出:{1, 2, 3, 6, 7, 8}
```
阅读全文