python数组交集
时间: 2023-09-10 11:10:18 浏览: 115
可以使用多种方法来获取Python数组的交集。
方法一:使用列表推导式和in操作符
```python
a = [2, 3, 4, 5]
b = [2, 5, 8]
tmp = [val for val in a if val in b]
print(tmp) # [2, 5]
```
方法二:使用set的intersection方法
```python
a = [2, 3, 4, 5]
b = [2, 5, 8]
print(list(set(a).intersection(set(b)))) # [2, 5]
```
方法三:使用集合的交集运算符&
```python
a = [2, 3, 4, 5]
b = [2, 5, 8]
print(list(set(a) & set(b))) # [2, 5]
```
以上是三种常见的方法获取Python数组的交集。你可以根据实际情况选择其中一种方法来使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Python 获得两个数组交集、并集、差集的方法](https://blog.csdn.net/sunny_day_day/article/details/126208046)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [两个数组的交集Python解法](https://blog.csdn.net/qq_43593534/article/details/127178466)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文