fishiwhj
fishiwhj

Reputation: 849

How to pass two parameters into lambda functions in map

I wish to use map to do the following thing:

res = []
arr1 = [1, 2, 3]
arr2 = [5, 0, 10]
for n, m in zip(arr1, arr2):
    res.append(n - 0.5 * m)

This is equivalent to do in list comp:

res = [n - 0.5 * m for n, m in zip(arr1 ,arr2)] 

But it fails using map:

res = map(lambda x, y: x - 0.5 * y, zip(arr1, arr2)) 

TypeError: <lambda>() takes exactly 2 arguments (1 given)

Is there a neat way to do this using map?

Upvotes: 0

Views: 3230

Answers (2)

ferhatelmas
ferhatelmas

Reputation: 3978

>>> map(lambda (x, y): x - 0.5 * y, zip(arr1, arr2)) 
[-1.5, 2.0, -2.0]

Like that you could take a tuple in lambda to fix it but I prefer what DTing suggested.

Upvotes: 1

dting
dting

Reputation: 39287

You zipped the arr1 and arr2 into a single argument

>>> res = []
>>> arr1 = [1, 2, 3]
>>> arr2 = [5, 0, 10]
>>> res = map(lambda x, y: x - 0.5 * y, arr1, arr2)
>>> res
[-1.5, 2.0, -2.0]

Upvotes: 4

Related Questions