Reputation: 1834
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()?
Upvotes: 5
Views: 1575
Reputation: 47392
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)]
Upvotes: 2
Reputation: 531075
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.
Upvotes: 3