Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the deepest list in list with abstract element?

Here I have some lists with any particular element (a, b, and c)

a = [2, 4, [9, 10]]
b = [1, 3, 5, 9, [11, 13, 14, 15, [16, 17, 19, 24]]]
c = [2, 4, [5, 11, 13, [14, 17, 29, [31, 19]]]]

npA = np.array(a, dtype = object)
npB = np.array(b, dtype = object)
npC = np.array(c, dtype = object)

I am trying to get the deepest list in each list a, b, c

print(npA[-1]) # it shows [9,10]
print(npB[-1][-1]) # it shows [16, 17, 19, 24]
print(npC[-1][-1][-1]) # it shows [31, 19]

How do get the generalization of this problem? or is there any built-in function of NumPy that can directly handle this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can solve this recursively, without numpy:

from typing import List

def deepest_list(l: List) -> List:
    last_item = l[-1]
    if isinstance(last_item, list):
        return deepest_list(last_item)
    return l

output:

deepest_list(c)
[31, 19]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading