交集 并集python
时间: 2024-01-06 10:25:36 浏览: 71
帮助计算并交交集的python脚本
以下是Python中求交集和并集的示例代码:
1. 求交集:
```python
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
set1 = set(list1)
set2 = set(list2)
intersection = set1.intersection(set2)
print("交集:", intersection) # 输出:{4, 5}
```
2. 求并集:
```python
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
set1 = set(list1)
set2 = set(list2)
union = set1.union(set2)
print("并集:", union) # 输出:{1, 2, 3, 4, 5, 6, 7, 8}
```
阅读全文