帮我写一个python函数,输入一个列表和一个元素,能够返回该元素在该列表中的索引,需要注意,该元素可能多次出现在列表中
时间: 2024-05-02 17:21:02 浏览: 13
以下是一个能够实现该功能的Python函数:
```python
def find_index(lst, elem):
index_lst = []
for i in range(len(lst)):
if lst[i] == elem:
index_lst.append(i)
return index_lst
```
该函数接受两个参数,分别是一个列表和一个元素。在函数内部,我们使用一个 for 循环遍历整个列表,如果列表中某个元素与传入的 elem 相等,则将该元素的索引加入到一个名为 index_lst 的列表中。最后,函数返回 index_lst,该列表中包含了 elem 在 lst 中出现的所有索引。
需要注意的是,如果 elem 在 lst 中没有出现过,那么该函数会返回一个空的列表。如果你只需要获取 elem 在 lst 中第一次出现的索引,可以将函数改写为:
```python
def find_index(lst, elem):
for i in range(len(lst)):
if lst[i] == elem:
return i
return -1
```
该函数会在找到第一个匹配的元素时立即返回其索引;如果 lst 中没有 elem,函数会返回 -1。
相关问题
帮我写一个python函数,能够返回某元素在一个列表中的索引
好的,以下是 Python 函数,可以返回某元素在一个列表中的索引:
```python
def find_index(lst, element):
try:
index = lst.index(element)
return index
except ValueError:
return -1
```
其中,`lst` 是列表,`element` 是要查找的元素。如果元素存在于列表中,函数将返回其索引;如果元素不存在于列表中,函数将返回 -1。
帮我写一个python函数,能够返回某字符元素在字符列表中的索引
好的,以下是 Python 函数,可以返回某个字符元素在字符列表中的索引:
```python
def find_index(char_list, char):
if char in char_list:
return char_list.index(char)
else:
return -1
```
其中,`char_list` 是字符列表,`char` 是要查找的字符元素。如果找到了,函数返回该元素在列表中的索引;如果没有找到,函数返回 -1。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)