Search code examples
pythonlistmultidimensional-arraysvd

How to convert 3D array to a list of 2D arrays in python?


I want to convert a 3D array (say size = 3x3x4) to a list of 3 (3x4) arrays. The 3D Array A in the else block is not the same type as in the if block.

I tried tolist() function, but it converts the 3D array to a list of lists, which is not desired.

X = np.random.randn(3, 3, 3)
for R in range(1,10):
    N = len(X.shape) 
    B = ()
    C = []

    for i in range(N):
        B += svd(X[i])
        C.append(B[3*i])
        
    C = np.array(C)
    if R <= np.shape(C)[2]:
        A = C[:,:,:R]
    else:
        A = np.concatenate((C[:,:,:np.shape(C)[2]],np.zeros((3,3,1))),axis=2)

Ideally, A = [np.random.randn(In, R) for In in X.shape]. But I am modifying this step by assigning left singular vectors of X to A.


Solution

  • A numpy array is an iterable, you you can easily convert it to a list:

    lst = list(A)
    

    Demo:

    >>> arr = np.arange(8).reshape(2,2,2)
    >>> arr
    array([[[0, 1],
            [2, 3]],
    
           [[4, 5],
            [6, 7]]])
    >>> list(arr)
    [array([[0, 1],
           [2, 3]]), array([[4, 5],
           [6, 7]])]