我有一个多参数函数。我简化了要映射的函数,这是我要测试的函数:
def _dist(I,J,X,Y):
return abs(I-X)+abs(J-Y)
Run Code Online (Sandbox Code Playgroud)
在某些情况下,我只想将X,Y保持不变,并分别在u_x和u_y上迭代I,J。我在下面写下一些东西(引发SyntaxError时)
new=map(_dist(,,cur.x(),cur.y()),u_x,u_y)
Run Code Online (Sandbox Code Playgroud)
其中cur.x()和cur.y()是恒定的。无论如何用map()做?
你不能使用列表理解吗?
new = [_dist(x,y,i,j) for x in ux for y in uy]
Run Code Online (Sandbox Code Playgroud)
其中i和j是你的常数。
请注意,这相当于
new = map(lambda (x,y): _dist(x,y,i,j), [(x,y) for x in ux for y in uy])
Run Code Online (Sandbox Code Playgroud)
但稍微短一些(并且可能更有效)。
编辑(回应@chepner的评论)-如果你想迭代 的压缩产品,ux那么uy你可以这样做
new = [_dist(x,y,i,j) for (x,y) in zip(ux,uy)]
Run Code Online (Sandbox Code Playgroud)
反而。注意区别——
>> 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)]
Run Code Online (Sandbox Code Playgroud)