0

Suppose I want to loop through the indices of a multi-dimensional array. What I currently have is:

import numpy as np
points = np.ndarray((1,2,3))
for x in range(points.shape[0]):
    for y in range(points.shape[1]):
        for z in range(points.shape[2]):
            print(x,y,z)

I would like to reduce the nesting and be able to loop over all indices of the multi-dimensional array in a simple one-liner. Could it also be written in the following form?

points = np.ndarray((1,2,3))
for (x, y, z) in ?? :
    print(x,y,z)
0

2 Answers 2

2

using iterools:

import itertools
x_dim, y_dim, z_dim = points.shape
for x, y, z in itertools.product(*map(range, (x_dim, y_dim, z_dim))):
    print(x,y,z)

or If you don't wanna use map write in this way:

for x, y, z in itertools.product(range(x_dim), 
                                 range(y_dim), 
                                 range(z_dim)):

0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
Sign up to request clarification or add additional context in comments.

Comments

0

Using numpy mgrid, we can do:

points = np.ndarray((1,2,3))
xs, ys, zs = points.shape
for [x, y, z] in np.mgrid[0:xs, 0:ys, 0:zs].T.reshape(-1,len(points.shape)):
    print(x,y,z)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.