找到两个数组的交集,用python写
时间: 2023-08-21 18:07:57 浏览: 60
你可以使用 Python 内置的 `set()` 函数和 `&` 运算符来查找两个列表的交集。
以下是一个示例代码:
```python
def get_intersection(a, b):
set_a = set(a)
set_b = set(b)
intersection = set_a & set_b
return list(intersection)
```
这个函数接受两个列表 `a` 和 `b` 作为输入,返回它们的交集。如果交集非空,则返回一个包含交集元素的列表;否则返回一个空列表。
你可以使用以下代码测试这个函数:
```python
a = [1, 2, 3, 4, 5]
b = [3, 4, 5, 6, 7]
c = [8, 9, 10]
print(get_intersection(a, b)) # [3, 4, 5]
print(get_intersection(a, c)) # []
```
输出结果为:
```
[3, 4, 5]
[]
```
需要注意的是,使用 `set()` 函数会导致原始列表中的元素顺序被打乱。如果需要保留原始列表中的元素顺序,可以使用列表推导式或者 `filter()` 函数来实现。
相关问题
两个数组不重复交集python
可以使用set的交集操作来实现两个数组的不重复交集,代码如下:
```python
a = [1, 2, 3, 4, 5]
b = [2, 4, 6, 8, 10]
set_a = set(a)
set_b = set(b)
intersection = set_a.intersection(set_b)
print(list(intersection))
```
输出为 `[2, 4]`,即两个数组的不重复交集。
找到两个array的交集,用python写
你可以使用 Python 的 `numpy` 库中的 `intersect1d()` 函数来查找两个数组的交集。
以下是一个示例代码:
```python
import numpy as np
def get_intersection(a, b):
intersection = np.intersect1d(a, b)
return intersection.tolist()
```
这个函数接受两个数组 `a` 和 `b` 作为输入,返回它们的交集。如果交集非空,则返回一个包含交集元素的列表;否则返回一个空列表。
你可以使用以下代码测试这个函数:
```python
a = np.array([1, 2, 3, 4, 5])
b = np.array([3, 4, 5, 6, 7])
c = np.array([8, 9, 10])
print(get_intersection(a, b)) # [3, 4, 5]
print(get_intersection(a, c)) # []
```
输出结果为:
```
[3, 4, 5]
[]
```
需要注意的是,使用 `numpy` 库需要先安装并导入库。如果你只需要找到两个列表的交集而不需要其他 `numpy` 库中的函数,可以使用前面提到的 Python 内置函数来实现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)