I want to loop through a three-dimensional array. Is there any alternative method which is more efficient (or faster) than the following?
for i, j, k in itertools.product(*map(xrange, (len(x), len(y), len(z))))
In this example, x, y and z are three one-dimensional arrays.
My source code is this, I do not want the value of lists.
for i, j, k in itertools.product(*map(xrange, (len(x0), len(y0), len(z0)))):
print "p[%d][%d][%d] = %d" % (x0[i], y0[j], z0[k], p[i][j][k])
p being the 3d-array
Why not just loop over the lists themselves instead?
for i, j, k in itertools.product(x, y, z):
You do not have indices now, you have the actual values:
>>> x, y, z = range(3), range(3, 6), range(6, 9)
>>> for i, j, k in itertools.product(x, y, z):
... print i, j, k
...
0 3 6
0 3 7
0 3 8
0 4 6
# .. ~ ..
2 4 8
2 5 6
2 5 7
2 5 8
If you have to have the indices too, just use enumerate():
>>> for (ii, i), (jj, j), (kk, k) in itertools.product(*map(enumerate, (x, y, z))):
... print (ii, i), (jj, j), (kk, k)
...
(0, 0) (0, 3) (0, 6)
(0, 0) (0, 3) (1, 7)
(0, 0) (0, 3) (2, 8)
(0, 0) (1, 4) (0, 6)
# .. ~ ..
(2, 2) (1, 4) (2, 8)
(2, 2) (2, 5) (0, 6)
(2, 2) (2, 5) (1, 7)
(2, 2) (2, 5) (2, 8)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With