First of all, hello, I have a little question. I'm trying to learn how to use lambda expression etc... I have this bit of code, it's an example that I need to replicate.
>>>something (lambda x:x+1, lambda y:y+10, [1, 2, 3, 4])
[2, 12, 4, 14]
I need that output and so far I got this:
l = [1,2,3,4]
def result(l):
o = l[0::2]
o2 = l[1::2]
p = map(lambda x:x+1,o)
p2 = map(lambda y:y+10,o2)
return p,p2
First of all I know I'm returning 2 separated lists, I'm trying to figure that one out.
Is there any way to do this without having p and p2 separated? Something like this:
p = map(lambda x,y: x+1 x+10, o,o2)
I know that line doesn't work I'm just trying to illustrate what I'm asking
You're using those lambda functions wrongly. Why use multiple lambda functions to process a simple list? You can use just one, with a list comprehension:
r = [1, 2, 3, 4]
func = lambda x: [v+1 if i%2==0 else v+10 for i,v in enumerate(x)]
func(r)
# [2, 12, 4, 14]
You may even prefer writing a proper function for this for readability.
Or better, you can even do without the lambda function altogether:
[v+1 if i%2 == 0 else v+10 for i,v in enumerate(x)]
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