使用递归查找列表中元素的索引 [英] Find index of element in a list using recursion

查看:90
本文介绍了使用递归查找列表中元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def index(L,v)
    ''' Return index of value v in L '''
    pass

我需要使用递归实现此功能的帮助. 递归的东西真的很新,所以任何建议都会有所帮助!

I need help with implementing this function using recursion. Really new to recursion stuff so any advice would help!

请注意,L是一个列表. v是一个值.

Note that L is a list. v is a value.

推荐答案

可行

def recursive_index(L, v):
    return 0 if L[0] == v else 1 + recursive_index(L[1:], v)

但是非常愚蠢(并且只有在值存在时才起作用)

but is pretty stupid (and will only work if the value exists)

您可以添加if v not in L: return -1使其适用于任何情况,但这甚至更糟.

You can add if v not in L: return -1 to make it work for any case, but that is even worst.

它真的必须递归吗?

这篇关于使用递归查找列表中元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆