Home > OS >  How to find the length of numpy arrays stored in a nested list?
How to find the length of numpy arrays stored in a nested list?

Time:01-25

I have a nested list of numpy arrays and want to find out the length of each array of all nested sublists. I tried this solution but could not solve my issue. My list here has two nested lists:

import numpy as np
big_list = [[np.array([[1., 2.], [0., 0.], [4., 4.]]),
             np.array([[0., 1.], [5., 6.]])],
            [np.array([[7., 7.]]),
             np.array([[5., 0.], [1., 7.]])]]

The first nested list has two arrays with lengths: 3 and 2. The second nested list has two arrays with lengths: 1 and 2. So, I want the final outcome to be a numpy array of lengths:

np.array([[3, 2], [1, 2]])

I tried the following for loops. It worked to somehow but I am looking for a more efficient way.

len_rough = np.array([])
for i in range (len(big_list)):
    for j in range (len(big_list[i])):
        len_each = len (big_list[i][j])
        len_rough = np.append(len_each, len_rough)
len_rough = len_rough[::-1]

CodePudding user response:

You can use a recursive function to determine the length of contained arrays. This works with any level of nesting.

def nested_len(obj, *, target_cls=np.ndarray):
    return [len(x) if isinstance(x, target_cls) else nested_len(x) for x in obj]
  •  Tags:  
  • Related