Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using Python 3.8 and I am attempting to write a lambda expression to square even numbers and cube odd numbers. So far, the code I have come for is as follows:

l = list(range(1, 11))

list(filter(lambda x: x ** 2 if x % 2 == 0 else x ** 3, l))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The syntax for if, else using lambda is:

lambda <arguments> : <Return Value if condition is True> if <condition> else <Return Value if condition is False>

However, the lambda expression is not doing the job. Help?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

The lambda is correct, but you need to map the function to the elements of the list, not filter it.

l = list(range(1, 11))

list(map(lambda x: x ** 2 if x % 2 == 0 else x ** 3, l))
# [1, 4, 27, 16, 125, 36, 343, 64, 729, 100]

Another more pythonic way is through list comprehension

f = lambda x: x ** 2 if x % 2 == 0 else x ** 3
[f(x) for x in l]

Or even better without the lambda expression:

[x ** 2 if x % 2 == 0 else x ** 3 for x in l]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...