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?
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)))
a = (1, 2)
b = (3, 4)
c = list(map(sum, zip(a, b)))
print(c)
[4, 6]
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))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With