0

Consider the following snippet:

a = np.ones((2,2,2,2,2))
for example in a:
    for row in example:
        for col in row:
            for box in col:
                print (box.shape)

Having so many nested fors makes for some very ugly code.

How can I get the same effect with only one explicit iteration?

Jsevillamol
  • 2,425
  • 2
  • 23
  • 46

1 Answers1

1

Reshape your array:

for box in a.reshape(16,2):
    print(box.shape)

A general solution:

for box in a.reshape(np.prod(a.shape[:-1]), a.shape[-1]):
     print(box.shape)

which will always iterate over one-before-the-last dimension of a.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54