两个列表的交集,如何用python写
时间: 2024-05-02 20:18:02 浏览: 11
可以使用Python内置的set()函数和&运算符来获得两个列表的交集。
示例代码:
```
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
intersection = set(list1) & set(list2)
print(intersection)
```
输出:
```
{4, 5}
```
解释:
首先使用set()函数把两个列表转换成集合,然后使用&运算符来获得交集。最后输出结果。
相关问题
找到两个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 内置函数来实现。
找到两个数组的交集,用python写
你可以使用 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()` 函数来实现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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_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)
![](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)