Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative triple for Python

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

like image 996
kshipuden Avatar asked Jan 28 '26 07:01

kshipuden


1 Answers

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)
like image 128
Martijn Pieters Avatar answered Jan 30 '26 21:01

Martijn Pieters