[Python] Finding all 1-d arrays within a numpy array

Discussão em 'Python' iniciado por Stack, Dezembro 18, 2024.

  1. Stack

    Stack Membro Participativo

    Given a numpy array of dimension n with each direction having length m, I would like to iterate through all 1-dimensional arrays of length m.

    For example, consider:

    import numpy as np
    x = np.identity(4)
    array([[1., 0., 0., 0.],
    [0., 1., 0., 0.],
    [0., 0., 1., 0.],
    [0., 0., 0., 1.]])


    then I would like to find all all 1-dimensional arrays with length 4. So the result should include all 4 rows, all 4 columns, and the 2 diagonals:

    [x[i,:] for i in range(4)] + [x[:,i] for i in range(4)] + [np.array([x[i,i] for i in range(4)])] + [np.array([x[3-i,i] for i in range(4)])]


    It's unclear to me how to generalize this to higher dimensional arrays since the position of the ":" in the slice needs to iterate as well. In a higher dimensional analogue with

    slices = [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

    we can get

    [x[i,j,:] for (i,j) in slices]


    but then I'm not sure how to proceed to iterate through the permutations of [i,j,:].

    Continue reading...

Compartilhe esta Página