python 怎么求并集
时间: 2023-12-14 13:04:11 浏览: 33
在 Python 中,可以使用 set 类型来求并集。set 是一个无序且不重复的集合,可以使用 union() 方法求两个 set 的并集。以下是示例代码:
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # 输出 {1, 2, 3, 4, 5}
```
另外,也可以使用 "|" 运算符来求两个 set 的并集,如下所示:
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set) # 输出 {1, 2, 3, 4, 5}
```
相关问题
python 取并集
在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}
python 集合 并集
以下是Python中计算集合并集的两种方法:
1. 使用union()方法
```python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
union_set = set1.union(set2, set3)
print("集合1、2、3的并集为:", union_set)
```
输出:集合1、2、3的并集为: {1, 2, 3, 4, 5}
2. 使用“|”运算符
```python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
union_set = set1 | set2 | set3
print("集合1、2、3的并集为:", union_set)
```
输出:集合1、2、3的并集为: {1, 2, 3, 4, 5}