用递归查找所有索引 [英] Find all indices with recursion
问题描述
我必须编写一个程序来查找列表或字符串中特定元素的所有索引值.我必须使用递归,而我的函数只能接受两个参数.
I have to write a program that finds all of the index values for specific element in list or a string. I have to use recursion, and my function can only take two arguments.
我的问题是我的程序只找到第一个索引然后停止.如何更改它以满足我的要求?
My problem is that my program finds only the first index and then stop. How can I change it to meet my requirements?
我的代码:
def find_all(L, v):
return 0 if L[0] == v else 1 + find_all(L[1:], v)
输入:
find_all( [1,2,3,4,2,4,5,2,1], 2)
find_all("hello好世界", "w")
所需的输出:
[1,4,7]
[6,16]
推荐答案
您可以使用 Python 的功能向后遍历列表并获取最后一个元素.然后将列表与 + 运算符放在一起.通过向后遍历列表,您可以在找到值时找到索引,而不是在从列表的开头移动到结尾时丢失它.
You can use Pythons ability to walk backwards through a list and grab the last element. Then put lists together with the + operator. By going through the list backwards you're able to find the indice when a value is found, rather than losing it when you move from the start of the list to the end.
def find_all(L, v):
if not L:
return []
result = []
if L[-1] == v:
result = [len(L)-1]
return find_all(L[:-1], v) + result
这篇关于用递归查找所有索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!