# 示例代码:使用 Python 实现类似 indexOf 的功能
def indexof(lst, item):
"""
在列表 lst 中查找元素 item 的索引。
如果找到,返回其索引;如果未找到,返回 -1。
参数:
lst (list): 要搜索的列表。
item: 要查找的元素。
返回:
int: 元素的索引或 -1(如果未找到)。
"""
try:
return lst.index(item)
except ValueError:
return -1
# 示例用法
my_list = [1, 2, 3, 4, 5]
item_to_find = 3
index = indexof(my_list, item_to_find)
print(f"Item {item_to_find} is at index {index} in the list.")
解释说明:
indexof 函数接受一个列表 lst 和一个要查找的元素 item。list.index() 方法来查找元素的索引。如果元素存在,则返回其索引;如果不存在,则抛出 ValueError 异常。ValueError 异常并返回 -1,表示元素未找到。indexof 函数并在列表中查找元素及其索引。下一篇:python demo
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站