Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: map() with partial arguments

Tags:

python

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()?

like image 806
YiFei Avatar asked Aug 11 '15 14:08

YiFei


People also ask

Can Map function have more than 2 arguments?

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.

How do you pass multiple arguments to a map in Python?

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.

How do I map two values in Python?

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.

Can map take multiple arguments?

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.


2 Answers

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.

like image 107
chepner Avatar answered Nov 03 '22 07:11

chepner


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)]
like image 45
Chris Taylor Avatar answered Nov 03 '22 07:11

Chris Taylor