[SciPy-user] Cycling the arrays

Warren Weckesser warren.weckesser@gmail....
Fri Mar 6 11:16:01 CST 2009


Marco,

The 'flat' attribute will give you an iterator over the elements of the
array.

For example,
--------------------------------------------------------------------
In [1]: from numpy.random import rand

In [2]: a = rand(2,3,4)

In [3]: a

Out[3]:
array([[[ 0.14858246,  0.75368248,  0.40294597,  0.42646085],
        [ 0.88369801,  0.00360736,  0.58419198,  0.13083728],
        [ 0.61364837,  0.43983396,  0.90157461,  0.21592489]],

       [[ 0.41765192,  0.08989583,  0.15821354,  0.53446492],
        [ 0.96593351,  0.21903464,  0.16993252,  0.74305159],
        [ 0.41083145,  0.40778255,  0.41558961,  0.59216869]]])

In [4]: for x in a.flat:
   ...:     print x, x**2
   ...:
   ...:
0.148582455636 0.0220767461228
0.75368248355 0.56803728601
0.402945971634 0.162365456056
0.426460853634 0.181868859683
0.883698012759 0.780922177755
0.00360735939407 1.3013041798e-05
0.584191982439 0.341280272346
0.130837280824 0.0171183940535
0.613648370127 0.376564322159
0.439833959795 0.193453912189
0.901574608475 0.812836774646
0.215924889889 0.0466235580736
0.41765191591 0.174433122864
0.0898958274532 0.0080812597935
0.158213541673 0.0250315247686
0.53446492479 0.285652755831
0.965933507608 0.93302754112
0.21903464047 0.047976173726
0.169932518795 0.0288770609439
0.743051591064 0.552125666983
0.410831453714 0.168782483361
0.407782547576 0.166286606108
0.415589605938 0.172714720563
0.592168688173 0.350663755252

In [5]:
------------------------------------------------------------

On Fri, Mar 6, 2009 at 11:03 AM, Marco <gaedol@gmail.com> wrote:

> Hi all,
>
> just a quick question: what is the fastest way to cycle inside an N
> dimensional array?
> I just want to visit each and every element in the N dimensional
> array, then do things.
>
> I can do it with N 'for' cycles, obviously.
> Is there a more compact and maybe faster way to do it?
>
> Thanks in advance,
>
> marco
> _______________________________________________
> SciPy-user mailing list
> SciPy-user@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20090306/ad37860f/attachment.html 


More information about the SciPy-user mailing list