5

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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)]

4 Comments

You want to zip ux and uy together; your code iterates over the cartesian product of ux and uy instead.
@chepner I thought that was the intention!
map(func, L1, L2) is equivalent to [func(L1[0], L2[0]), func(L1[1], L2[1]), ..., func(L1[-1], L2[-1])]
Ah, ok - I read the phrase "iterate I,J over u_x and u_y" which suggests cartesian product to me. I ignored the code because the OP admitted that they didn't know what they were doing ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.