Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python indexof

作者:逐鹿↘星恒   发布日期:2026-07-24   浏览:59

# 示例代码:使用 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
  • 使用 Python 内置的 list.index() 方法来查找元素的索引。如果元素存在,则返回其索引;如果不存在,则抛出 ValueError 异常。
  • 捕获 ValueError 异常并返回 -1,表示元素未找到。
  • 示例用法展示了如何调用 indexof 函数并在列表中查找元素及其索引。

上一篇:python isdigit()函数

下一篇:python demo

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

python集合中的元素可以是列表

staticmethod在python中有

python 保存json文件

python的assert基本用法

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站