查找列表相同元素位置Python
时间: 2023-11-19 12:07:58 浏览: 25
Sure, I can help you find the position of the same elements in a list using Python. Here's an example code snippet:
```
my_list = [1, 2, 3, 2, 4, 1, 5, 6, 5]
duplicates = []
for i in range(len(my_list)):
if my_list[i] in my_list[i+1:] and my_list[i] not in duplicates:
duplicates.append(my_list[i])
print("Duplicate element:", my_list[i])
print("Position(s):", [j for j in range(len(my_list)) if my_list[j] == my_list[i]])
```
This will output:
```
Duplicate element: 1
Position(s): [0, 5]
Duplicate element: 2
Position(s): [1, 3]
Duplicate element: 5
Position(s): [6, 8]
```
Hope this helps!
相关问题
python查找列表元素,并输出位置
可以使用Python内置函数`index`来查找列表中指定元素的位置,例如:
```python
my_list = [10, 20, 30, 40, 50]
index = my_list.index(30)
print(index)
```
输出结果为:
```
2
```
如果要查找列表中多个相同元素的位置,可以使用循环遍历列表,如下所示:
```python
my_list = [10, 20, 30, 20, 50]
for i in range(len(my_list)):
if my_list[i] == 20:
print(i)
```
输出结果为:
```
1
3
```
python list 查找相同元素
Python中可以使用循环和条件语句来查找列表中相同的元素。具体方法如下:
1. 定义一个列表,例如:lst = [1, 2, 3, 4, 5, 2, 3, 6, 7, 8, 9, 2, 3]
2. 定义一个空列表,用于存储相同的元素,例如:same_lst = []
3. 使用for循环遍历列表lst中的每个元素,判断该元素是否在same_lst中,如果不在,则继续判断lst中是否有相同的元素,如果有,则将该元素添加到same_lst中,例如:
for i in lst:
if i not in same_lst:
if lst.count(i) > 1:
same_lst.append(i)
4. 最后输出same_lst即可,例如:print(same_lst)
以上就是Python中查找列表中相同元素的方法。