On Mon, Sep 12, 2011 at 01:52, David Froger <[email protected]> wrote: > Hy everybody, > > I'm wondering what is the (best) way to apply the same function to multiple > arrays. > > For example, in the following code: > > from numpy import * > > def f(arr): > return arr*2 > > a = array( [1,1,1] ) > b = array( [2,2,2] ) > c = array( [3,3,3] ) > d = array( [4,4,4] ) > > a = f(a) > b = f(b) > c = f(c) > d = f(d) > > I would like to replace : > > a = f(a) > b = f(b) > c = f(c) > d = f(d)
This is usually the best thing to do for few variables and simple function calls. If you have many more variables, you should be keeping them in a list or dict instead of individual named variables. If you have a complicated expression, wrap it in a function. You could also do something like this: a,b,c,d = map(f, [a,b,c,d]) but it's harder to understand what is going on that just using four separate lines and no easier to maintain. Don't use eval() or locals(). -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco _______________________________________________ NumPy-Discussion mailing list [email protected] http://mail.scipy.org/mailman/listinfo/numpy-discussion
