首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Python中查找列表中某些值的第一个和最后一个索引

作为一个云计算领域的专家,我可以告诉你,在Python中查找列表中某些值的第一个和最后一个索引可以使用以下方法:

代码语言:python
复制
def find_first_last_index(lst, value):
    first_index = -1
    last_index = -1
    for i in range(len(lst)):
        if lst[i] == value:
            if first_index == -1:
                first_index = i
            last_index = i
    return first_index, last_index

这个函数接受一个列表lst和一个值value作为输入,并返回一个元组,其中包含了valuelst中第一次出现的索引和最后一次出现的索引。如果valuelst中没有出现,则返回(-1, -1)

例如,如果我们有以下列表:

代码语言:python
复制
lst = [1, 2, 3, 2, 4, 2, 5]

我们可以使用find_first_last_index函数来查找2的第一个和最后一个索引:

代码语言:python
复制
first_index, last_index = find_first_last_index(lst, 2)
print(first_index, last_index)  # 输出:1 5

这个函数可以用于任何Python列表,并且不依赖于任何特定的云计算平台。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券