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.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With