I got a multi-argument function. I simplified the function to map, and here's my function to test with:
def _dist(I,J,X,Y):
return abs(I-X)+abs(J-Y)
And in some case, I just want to hold X,Y as constant and iterate I,J over u_x and u_y, respectively. I write down something below (while SyntaxError raised)
new=map(_dist(,,cur.x(),cur.y()),u_x,u_y)
where the cur.x() and cur.y() are constant. Anyway to do it with map()?
The map function has two arguments (1) a function, and (2) an iterable. Applies the function to each element of the iterable and returns a map object. The function can be (1) a normal function, (2) an anonymous function, or (3) a built-in function.
To pass multiple arguments to the map() function:Pass the handler function and the arguments to the functools. partial() method. Pass the result and the iterable to the map() function. The handler function will get called the arguments on each iteration.
Passing Multiple Arguments to map() function Suppose we pass n iterable to map(), then the given function should have n number of arguments. These iterable arguments must be applied on given function in parallel. In multiple iterable arguments, when shortest iterable is drained, the map iterator will stop.
Using the Python map() function with multiple arguments functions. Besides using the Python map() function to apply single argument functions to an iterable, we can use it to apply functions with multiple arguments.
You can partially apply _dist
:
from functools import partial
_mapfunc = partial(_dist, X=cur.x(), Y=cur.y())
new = map(_mapfunc, u_x, u_y)
although Chris Taylor's list comprehension is probably more efficient.
Can you not use a list comprehension?
new = [_dist(x,y,i,j) for x in ux for y in uy]
where i
and j
are your constants.
Note that this is equivalent to
new = map(lambda (x,y): _dist(x,y,i,j), [(x,y) for x in ux for y in uy])
but somewhat shorter (and probably more efficient).
Edit (in response to @chepner's comment) - if you want to iterate through the zipped product of ux
and uy
then you can do
new = [_dist(x,y,i,j) for (x,y) in zip(ux,uy)]
instead. Note the difference -
>> ux = [1, 2, 3]
>> uy = [4, 5, 6]
>> [(x,y) for x in ux for y in uy]
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
>> zip(ux, uy)
[(1, 4), (2, 5), (3, 6)]
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