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

2024-06-26 13:47:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

嗨,我想知道是否有人能帮我学Python。我试图创建一个代码,以递归的方式返回列表中最后一次出现的项的最后一个索引。所以在一个列表[1,2,3,4,5,2]中,最后一个应该返回4。它只接受两个变量,即列表和它正在搜索的项。如果没有找到匹配的变量,则返回-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)

Tags: andin列表indexreturnifplaceitem
3条回答

如果不需要递归,可以使用以下命令:

def find_last(lst,item):
    try:
       return len(lst) - next(i for i,elem in enumerate(reversed(lst),1) if elem == item)
    except StopIteration:
       return -1


a = [1,2,3,4,5,4,3]
idx = find_last(a,4)
print a[idx]
print find_last(a,6)

我不是百分之百确定我知道你想要什么。你说“。。。在一个[1,2,3,4,5,2]的列表中,它应该返回4…“这让我有点困惑;我想您应该返回指定的item的最后一次出现的索引。因此,要使4成为指定列表中的结果,item必须是5。在

如前所述,递归函数在这里并不是最有效或最具python的解决方案。我更喜欢像nneonneo's answer中的第一个解决方案。在

但是,如果它必须是递归的,我相信下面的代码可以满足您的需要。在递归调用中传递列表时,您需要使用[1:]作为索引范围,而不是从前面单步执行列表:

def lstIndex(lst, item):
    if len(lst) == 0:
        return -1
    elif lst[-1] == item:
        return len(lst) - 1
    else:
        return lstIndex(lst[0:-1], item)

我测试了以下内容:

^{pr2}$

输出如下:

5
0
2
3
4
-1
-1

短迭代解:

try:
    return (len(lst)-1) - lst[::-1].index(item)
except ValueError:
    return -1

但是,由于您是显式地寻找递归的解决方案,所以我将向您展示如何递归地完成它。然而,它将是有效的;如果你想要一个好的,有效的,Python式的解决方案,你应该使用一个迭代的解决方案,如其他人所示(或上面的一个)。在

实际上有几种方法可以做到这一点。您可以使用一个helper函数,该函数接受一个额外的参数,指定找到该值的最后一个索引:

^{pr2}$

您可以不使用helper函数:

def list_rfind(lst, item):
    if not lst:
        return -1

    res = list_rfind(lst[1:], item)
    if res >= 0:
        return res+1
    elif lst[0] == item:
        return 0
    else:
        return -1

相关问题 更多 >