python求两个集合的并集
时间: 2023-12-24 08:45:41 浏览: 57
可以使用 Python 内置的 set 类型进行集合操作,可以通过 `|` 运算符求两个集合的并集,示例代码如下:
```python
set1 = {1, 2, 3}
set2 = {2, 3, 4}
union_set = set1 | set2 # 求并集
print(union_set) # 输出 {1, 2, 3, 4}
```
其中 `|` 运算符表示求并集,将两个集合合并成一个新的集合。
相关问题
python 2个list求并集
可以使用 set() 函数将两个列表转换成集合,然后使用 union() 方法求并集,再将结果转换回列表即可。示例代码如下:
```python
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
# 将列表转换成集合,求并集,再转换回列表
union_list = list(set(list1).union(set(list2)))
print(union_list) # 输出:[1, 2, 3, 4, 5, 6]
```
注意:集合是无序的,因此并集的顺序可能与原列表不同。
Python计算两个集合的交集并集差集
假设有两个集合A和B,可以用Python的set类型表示它们。交集、并集、差集的计算可以使用set类型提供的交集运算符&、并集运算符|、差集运算符-,具体实现如下:
```python
A = set([1, 2, 3, 4])
B = set([3, 4, 5, 6])
# 计算交集
intersection = A & B
print("交集:", intersection)
# 计算并集
union = A | B
print("并集:", union)
# 计算差集
difference = A - B
print("差集:", difference)
```
上述代码输出结果:
```
交集: {3, 4}
并集: {1, 2, 3, 4, 5, 6}
差集: {1, 2}
```