Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

numpy

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?

like image 839
sempraEdic Avatar asked Oct 25 '25 13:10

sempraEdic


1 Answers

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]
like image 55
Tom McLean Avatar answered Oct 27 '25 02:10

Tom McLean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!