首页 > 解决方案 > Python - 使用递归查找列表中给定元素的索引

问题描述

def ind(e, L):
    if e not in L:
        return 0
    else:
        return 1 + ind(e, L[:1]) 
assert ind(42, [55, 77, 42, 12, 42, 100]) 

我想要索引(所以在这种情况下我需要 2),但代码似乎总是给我数字。我也不能在 Python 中使用索引函数。

如果你有时间请帮忙。

标签: pythonlistrecursionindexing

解决方案


def ind(e, L):
    if e == L[0]:
        return 0
    else:
        return 1 + ind(e, L[1:])

推荐阅读