python查找列表元素位置
时间: 2023-06-01 22:02:15 浏览: 117
Python中可以使用index()函数来查找列表中某个元素的位置。
例如,假设有一个列表a=[1,2,3,4,5],想要查找元素3的位置,可以使用以下代码:
```
a=[1,2,3,4,5]
index = a.index(3)
print(index)
```
输出结果为:
```
2
```
注意:如果列表中不存在要查找的元素,则会抛出ValueError异常。
相关问题
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
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!