Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining map with zip through lambda

Tags:

python

I'm trying to write a function for adding 2D vectors. I'm trying to combine the map() function, getting a list using the zip() function (which will zip 2 tuples).

This is the code:

a = (1, 2)
b = (3, 4)
c = list(map(lambda x, y: x+y, list(zip(a, b))))
print(c)

So the way I see it, zip(a, b) returns a zip object containing the following tuples: (1, 3), (2, 4). It is then converted to a list. I'm getting the following error:

TypeError: () missing 1 required positional argument: 'y'

So my guess is that the lambda function is not taking the second number in each tuple.

Is there any way to do this?

like image 968
fishamit Avatar asked Dec 03 '22 20:12

fishamit


2 Answers

Only one parameter for lambda like:

c = list(map(lambda x: sum(x), zip(a, b)))

But once we are using sum, we can map it directly like:

c = list(map(sum, zip(a, b)))

Test Code:

a = (1, 2)
b = (3, 4)
c = list(map(sum, zip(a, b)))
print(c)

Result:

[4, 6]
like image 106
Stephen Rauch Avatar answered Dec 27 '22 06:12

Stephen Rauch


In Python2, you can use specific unpacking syntax in a lambda:

a = (1, 2)
b = (3, 4)
c = list(map(lambda (x, y): x+y, list(zip(a, b))))

However, in Python3, you will have to use sum:

c = list(map(lambda x_y: sum(x_y), list(zip(a, b))))
like image 37
Ajax1234 Avatar answered Dec 27 '22 06:12

Ajax1234