python选出两个list中相同的元素,同时要保证元素的相对位置不变
时间: 2023-05-15 09:07:38 浏览: 48
可以使用列表推导式和enumerate函数来实现:
```python
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
result = [x for i, x in enumerate(list1) if x in list2 and list2.index(x) == i]
print(result) # 输出 [3, 4, 5]
```
在这个代码中,我们首先使用enumerate函数来遍历list1中的元素,并获取它们的索引。然后,我们使用列表推导式来筛选出那些既在list1中出现过,又在list2中出现过,并且它们在list1和list2中的位置相同的元素。最后,我们将结果存储在result变量中并输出。
相关问题
python选出两个list中相同的元素,同时要保证顺序
可以使用列表推导式和enumerate函数来实现:
```python
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
result = [x for i, x in enumerate(list1) if x in list2 and list2.index(x) == i]
print(result) # 输出 [3, 4, 5]
```
在这个代码中,我们首先使用enumerate函数来获取list1中每个元素的索引i和值x,然后判断x是否同时存在于list2中,并且在list2中的索引也为i,这样就可以保证顺序相同。最后将符合条件的元素添加到结果列表中。
python选出两个list中相同的元素,同时要保证元素的相对位置不败你
可以使用以下代码实现:
```python
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
result = [x for x in list1 if x in list2]
print(result)
```
输出结果为:
```
[3, 4, 5]
```
这段代码使用了列表推导式,遍历了 list1 中的每个元素,如果该元素也在 list2 中出现,则将其加入到结果列表中。由于列表推导式的特性,结果列表中的元素顺序与 list1 中的相对位置保持一致。
相关推荐
![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)