Reputation: 2543
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 for
s makes for some very ugly code.
How can I get the same effect with only one explicit iteration?
Upvotes: 0
Views: 251
Reputation: 20414
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
.
Upvotes: 1