0

Consider the following snippet of code:

n_samples, n_rows, n_cols, n_boxes_per_cell, _ = Y_pred.shape
    for example in range(n_samples):
        for x_grid in range(n_rows):
            for y_grid in range(n_cols):
                for bnd_box in range(n_boxes_per_cell):
                    bnd_box_label = Y_pred[example, x_grid, y_grid, bnd_box]
                    do_some_stuff(bnd_box_label, x_grid, y_grid)

How can I get functionally equivalent code with at most one explicit iteration? Notice that I need the indices x_grid and y_grid.

2 Answers 2

3

You can use np.ndindex:

for example, x_grid, y_grid, bnd_box in np.ndindex(Y_pred.shape[:4]):
    etc.
Sign up to request clarification or add additional context in comments.

Comments

1

I'm not sure if this is what you're looking for, but you can always build a generator out of multiple iterables:

all_combinations = ((a, b, c, d) for a in range(n_samples)
                                 for b in range(n_rows) 
                                 for c in range(n_cols) 
                                 for d in range(n_boxes_per_cell))

for examples, x_grid, y_grid, bnd_box in all_combinations:
    do stuff

This is the same as using itertools.product(*iterables) and valid for any iterable, not just iteration over indices/integers.

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.