Skip to main content
 首页 » 编程设计

python之如何返回列表 Python 的最后一个索引

2025年05月04日12虾米姐

<分区>

Possible Duplicate:
Finding first and last index of some value in a list in Python

您好,我想知道是否有人可以帮助我学习 Python。我正在尝试创建一个代码,以递归方式返回列表中最后一次出现的项目的最后一个索引。所以在列表 [1,2,3,4,5,2] 中,最后一个应该返回 4。它只接受 2 个变量,即列表和它正在搜索的项目。如果没有找到任何匹配的变量,则返回 -1。

到目前为止我有这个:

def lstIndex(lst, item): 
    if len(lst) == 0: 
        return -1 
    place = lst[0] 
    if place == item: 
        print(place) 
        #just return the index 
        return lst.index(place) 
    else: 
        return lstIndex(lst[1:],item)