Home > Blockchain >  How to find innermost level of a list in python
How to find innermost level of a list in python

Time:11-28

So, say you had a list such as [0,[0,[0,1]]] or [[[0],1],1], how would I write a piece of code to find the innermost entries, so in the first example it should return [0,1], while in the second example it should return [0]. The only way I know how to do it is something like this: [k for k in [i for i in..., and I tried this, but I couldn't find a way to generalise it to arbitrarily nested arrays. Does anyone know how to do this using python? Thanks.

CodePudding user response:

This is a relatively easy problem using recursion. Iterate over your data, if the item is a list call the function within itself using that level, otherwise continue. Once the loop is complete just return that current level which is our break out condition which will only be reached when that level has no inner lists.

def innermost(data):
    for item in data:
        if isinstance(item, list):
            return innermost(item)
        else:
            continue
    return data


innermost([0,[0,[0,1]]])
> [0, 1]

innermost([[[0],1],1])
> [0]

CodePudding user response:

I have come up with a solution which finds the deepest level and the contents of the deepest level in a python list of unknown number of hierarchies.

a = [0,[0,[0,1]], 1, [1,2,[5,6,9,[6,6,6,6]]]

depths = []
maxLevel = 0
deepestList = []

def findDeepest(arr, level):
    global depths
    global maxLevel
    global deepestList
    for item in arr:
        if type(item) == list:
            level = level   1
            depths.append(level)
            if level > maxLevel:
                maxLevel = level
                deepestList = item
            findDeepest(item, level)
    return max(depths), deepestList
    
results = findDeepest(a, 0)

print("Deepest level is: ", results[0])
print("Deepest list is: ",results[1])
  • Related