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

时间:2012-10-20 03:47:35

标签: python recursion indexing

  

可能重复:
  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)

5 个答案:

答案 0 :(得分: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 :(得分:3)

短迭代解决方案:

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

但是,既然您正在寻找递归解决方案,我将向您展示如何以递归方式完成。但是,它是高效的;如果你想要一个漂亮,高效的Pythonic解决方案,你应该像其他人一样(或上面的那个)使用迭代解决方案。

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

def list_rfind(lst, item):
    def list_rfind_helper(i, item, last=-1):
        if i >= len(lst): return last
        if lst[i] == item: last = i
        return list_rfind_helper(i+1, item, last)

    return list_rfind_helper(0, item)

你可以在没有辅助功能的情况下完成:

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

答案 2 :(得分:1)

lst = [1, 2, 3, 4, 3, 4]

findLast(lst, 4)

def findLast(lst, item):
    for i, val in enumerate(reversed(lst)):
        if val == item:
            return len(lst) - (i + 1)  # Return index of matched item

    return -1

答案 3 :(得分:1)

为了完整性:

def list_rfind(lst, item):
    return (len(lst)-1) - sum(1 for _ in iter(reversed(lst).next, item))

答案 4 :(得分:0)

我不是100%确定我知道你想要什么。你的陈述“......在[1,2,3,4,5,2]列表中最后一个应该返回4 ......”让我有点困惑;我想你想要返回指定item的最后一次出现的索引。因此,要将4作为指定列表中的结果,item必须为5。

如其他地方所述,递归函数不是最有效或Pythonic解决方案。我更喜欢nneonneo's answer中的第一个解决方案。

但是,如果它必须是递归的,我相信下面的代码可以得到你想要的。而不是从前面单步执行列表(通过使用[1:]),在递归调用中传递列表时,需要使用[:-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)

我测试了以下内容:

the_list = [1,2,3,4,5,2]
print lstIndex(the_list, 2)
print lstIndex(the_list, 1)
print lstIndex(the_list, 3)
print lstIndex(the_list, 4)
print lstIndex(the_list, 5)
print lstIndex(the_list, 6)
print lstIndex(the_list, 0)

使用以下输出:

  

5
  0
  2
  3
  4
  -1
  -1