python取两个list的并集
时间: 2023-10-09 11:08:27 浏览: 56
可以使用set()函数来取两个list的并集,然后再将其转换回list类型。
示例代码:
```
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
union = list(set(list1).union(set(list2)))
print(union)
```
输出结果为:
```
[1, 2, 3, 4, 5, 6]
```
其中set()函数用来将list转换为集合类型,然后使用union()函数求并集,最后再将集合类型转换为list类型。
相关问题
python取两个数组的并集
可以使用 set 的 intersection 方法来取得两个数组的交集。示例如下:
```python
arr1 = [1, 2, 3, 4, 5]
arr2 = [4, 5, 6, 7, 8]
intersect = set(arr1).intersection(arr2)
print(list(intersect)) # 输出 [4, 5]
```
如果想要求并集,可以使用 set 的 union 方法,示例如下:
```python
arr1 = [1, 2, 3, 4, 5]
arr2 = [4, 5, 6, 7, 8]
union = set(arr1).union(arr2)
print(list(union)) # 输出 [1, 2, 3, 4, 5, 6, 7, 8]
```
也可以直接使用 | 运算符来求并集,示例如下:
```python
arr1 = [1, 2, 3, 4, 5]
arr2 = [4, 5, 6, 7, 8]
union = set(arr1) | set(arr2)
print(list(union)) # 输出 [1, 2, 3, 4, 5, 6, 7, 8]
```
注意,求并集和交集时,先将数组转化为 set 类型,否则可能会出现重复元素。
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]
```
注意:集合是无序的,因此并集的顺序可能与原列表不同。