python 取并集
时间: 2024-03-30 22:32:35 浏览: 34
在Python中,可以使用set类型的内置函数来取两个集合的并集。集合是一种无序且不重复的数据结构。
以下是取并集的几种方法:
1. 使用union()函数:可以使用union()函数来取两个集合的并集。示例代码如下:
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set)
```
输出结果为:{1, 2, 3, 4, 5}
2. 使用|运算符:可以使用|运算符来取两个集合的并集。示例代码如下:
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set)
```
输出结果为:{1, 2, 3, 4, 5}
3. 使用update()函数:可以使用update()函数将一个集合添加到另一个集合中,从而实现并集的效果。示例代码如下:
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.update(set2)
print(set1)
```
输出结果为:{1, 2, 3, 4, 5}