如何运用函数查找首次出现时间
- 编程技术
- 2025-02-02 00:03:43
- 1
要使用函数查找一个元素在列表中首次出现的时间,我们可以编写一个简单的Python函数来实现这个功能。以下是一个示例函数,它接受一个列表和一个要查找的元素作为参数,然后返...
要使用函数查找一个元素在列表中首次出现的时间,我们可以编写一个简单的Python函数来实现这个功能。以下是一个示例函数,它接受一个列表和一个要查找的元素作为参数,然后返回该元素首次出现的位置索引。
```python
def find_first_occurrence(lst, element):
for index, current_element in enumerate(lst):
if current_element == element:
return index
return -1 如果元素不在列表中,返回-1
示例使用
my_list = [3, 5, 2, 5, 1, 5, 4]
element_to_find = 5
调用函数并打印结果
index = find_first_occurrence(my_list, element_to_find)
print(f"Element {element_to_find
本文由夕逆IT于2025-02-02发表在夕逆IT,如有疑问,请联系我们。
本文链接:http://xinin56.com/bian/425210.html
本文链接:http://xinin56.com/bian/425210.html
上一篇:如何表示某天所属的周一