递归遍历列表(python) [英] Recursively going through a list (python)
问题描述
说我有一个列表x = [1、2、3、4]
Say I have a list x = [1, 2, 3, 4]
是否有一种递归方法可以在列表中查找值?
Is there a recursive method where i can go through the list to find the value?
我希望最终能够将列表(或嵌套列表)中的返回值与任意数字进行比较,以查看它是否匹配.
I want to ultimately be able to compare a returned value in the list, (or nested list) to an arbitrary number to see it it matches.
我可以考虑使用for循环执行此操作的方法,但是我很难想象使用递归方法来执行相同的操作.我知道我无法设置计数器来跟踪我在列表中的位置,因为递归调用函数只会每次都重置计数器.
I can think a way to do this using a for loop, but i have trouble imagining a recursive method to do the same thing. I know that I can't set a counter to keep track of my position in the list because calling the function recursively would just reset the counter every time.
我当时以为我可以将函数的基本情况设置为数字和len 1列表之间的比较.
I was thinking I could set my base case of the function as a comparison between the number and a list of len 1.
我只想要一些提示.
推荐答案
这不是在Python中执行操作的方法,但是可以肯定-您可以递归遍历列表列表:
This is not the way to do things in Python, but surely - you can traverse a list of lists recursively:
def findList(lst, ele):
if not lst: # base case: the list is empty
return False
elif lst[0] == ele: # check if current element is the one we're looking
return True
elif not isinstance(lst[0], list): # if current element is not a list
return findList(lst[1:], ele)
else: # if current element is a list
return findList(lst[0], ele) or findList(lst[1:], ele)
这篇关于递归遍历列表(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!