Home > Blockchain >  How to get the deepest list in list with abstract element?
How to get the deepest list in list with abstract element?

Time:04-04

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?

CodePudding user response:

You can solve this recursively, without numpy:

from typing import List

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

output:

deepest_list(c)
[31, 19]
  • Related