开发者

Recursive Nested Lists

开发者 https://www.devze.com 2023-03-03 22:08 出处:网络
I\'m having trouble getting my head around a problem on recursive nested lists. The problem; need to define a procedure to access a nested list to an arbitrary depth. It would take an nested list and

I'm having trouble getting my head around a problem on recursive nested lists. The problem; need to define a procedure to access a nested list to an arbitrary depth. It would take an nested list and an index, and return the part of the list at that index. From this given function, recursively find the value at the given index.

For example

Well here is a better visual representation. To select the element 9 out of it, we need to do something like nested[3][1]

    nested = \
    [[[1, 2],
      3],
     [4,
      [5, 6]],
     7,
     [8, 9, 10]]

recursive_开发者_StackOverflowfunc(nested_list, [3,1]) #recursive function definition, the second argument is the index at which the data needs to be retrieved.  
>>> 9 #so given the function an index of [3,1] would return 9

Any help to point me in the right direction would be grateful


This may do you, but I'm still not 100% sure what you are looking for...

>>> def findItem(nested, pos):
    if pos[0] == 1:
        return nested[pos[1]-1]
    else:
        nextLevelDown = []
        for item in nested:
            if type(item) == type([]):
                nextLevelDown = nextLevelDown + item
        return findItem(nextLevelDown, [pos[0]-1, pos[1]])

>>> findItem([[[1, 2], 3], 4], [3, 1])
1
>>> findItem([[[1, 2], [3]], 4], [3, 3])
3
>>> findItem([[[1, 2], [3]], 4], [2, 2])
[3]

UPDATE: So after much back and forth, I finally understand the question, and it is much simpler than it originally seemed, all you need is:

>>> def recursiveRef(nested, idxList):
    if len(idxList) > 1:
        return recursiveRef(nested[idxList[0]], idxList[1:])
    return nested[idxList[0]] 

>>> recursiveRef([[[1, 2], 3], [4, [5, 6]], 7, [8, 9, 10]], [3, 1])
9


If I understand this correctly, you want simply turn nested list into non-nested? And then check the index? If so, then you can try something like this (I don't have python at the moment, so treat it like a pseudocode):

def unwrap_list(list, result):
   if type(list) == type([]):
      for value in list:
         unwrap_list(value, result)
   else:
      result.append(list)

Make sure, to define variable unwrapped = [] before calling this function and use unwrap_list(list, unwrapped). The result will be stored in variable unwrapped.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号