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

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

lambda - Lamdba expression Python to square even numbers and cube odd numbers

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...