Recursively going through a list (python)

瘦欲@ 提交于 2019-12-22 11:16:50

问题


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.

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.

I was thinking I could set my base case of the function as a comparison between the number and a list of len 1.

I just want some hints really.


回答1:


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)



回答2:


Recursive functions are idiomatic for when you have a linked list. Python lists are more like arrays. But it's still possible to handle a Python list with a recursive function -- there's no real utility, but it can be interesting as an exercise.

You start with a full list, and your base case is when the list is empty. Traverse the list by passing the list in as an argument, using x.pop() to simultaneously fetch and remove the first item in the list, evaluate the popped item, and then pass the list (now shorter) into the same function.

Edit: actually, on second thought, you would be better off not using x.pop() and instead peeking at the first value and passing the remainder in a slice. This would be grossly inefficient, because you're copying the list every time you slice, but it's better than destructively consuming the list inside your recursive function, unless that's a desired side-effect.




回答3:


Well you will have two base cases:

1) You have reached the end of the list => return false.

2) Your current element is the element you are looking for => return true (or the element or its position, whatever you are interested in).

The thing you have to do all the time is check both base cases on the current element and apply the function recursively on the next element in the list if neither one of the base cases applied.



来源:https://stackoverflow.com/questions/21563271/recursively-going-through-a-list-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!