Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through List of nested List of lists

Tags:

python

I have a nested list of lists occurring in the form of

 A = [[a,b],[c,d]] or [[[a,b],[c,d]]] or [[[[a,b],[c,d]]]] or [[[[[a,b],[c,d]]]]] 

and so on. These forms of A don't occur at the same time.

How can I code to peel the list, no matter how nested A may be, and obtain only:

[a,b] 
[c,d]

I tried this:

def Peel_list(Features):
    try:
        for lon,lat in Features:
            print((lon,lat))
    except:
        for Feature in Features:
            for t_list in Feature:
                for A in t_list:
                    for lon,lat in A:
                        print((lon,lat))
    return()

But it only works for limited A.

like image 445
Anthony Ifeanyi Avatar asked Sep 17 '25 07:09

Anthony Ifeanyi


1 Answers

Generally when we want to deal with a problem of arbitrarily nested objects recursion is a good place to start. Here we want to keep "digging down" until we hit the base case, in our case any non list value. The code looks something like this

test = [1, [3,4],[[5]], [[[6]]]]
peeled = []

def peel(myList, peeled):
    for val in myList:
        if isinstance(val, list):
            if not isinstance(val[0], list):
                peeled.append(val)
            else:
                peel(val, peeled)
        else:
            peeled.append(val)


peel(test, peeled)
print(peeled)

This will give you something like

[1, [3, 4], [5], [6]]

like image 145
Mitch Avatar answered Sep 19 '25 11:09

Mitch