As an Engineer — Python Advanced Lambda

2023/04/05閱讀時間約 4 分鐘
A lambda function is a small anonymous function and can only have one expression.

Introduction

lambda is an anonymous and one-line function. It helps you replace simple functions with one line, achieving the simplicity that the Python programming language is most proud of.
Syntax:
lambda arguments : expression
Arguments are the variables you pass to this function, and expression are the logic your function performs.

Explanation

e.g. 1
def example1(x):
return x
lambda x : x
Let’s look at the first example, we can know that this function is called example1, and it will return the variable x passed in by the user.
lambda is an anonymous function, so it doesn’t need to be named example1. Before the : is the variable x passed in by the user, and after the : is the return value, because there is no math, so the expression ends here.
e.g.2
def example2(x):
if x > 10:
return x
else:
return 10
lambda x : x if x > 10 else 10
The second example should feel the power of lambda. When the original five-line program code is written in lambda, only one line is needed.
Analyze the way of writing lambda. The same user passes in a variable x, and returns x, but with some calculations. Returns x if x > 10, otherwise returns 10.
Right now, you should be familiar with the syntax of lambda. Then we combine some python syntax to write more magical lambda functions.
e.g.3
def example3(x):
y = []
for i in x:
y.append(i + 1)
return y
lambda x: list(map(lambda i : i+1, x))
By using a map instead of a for loop, one line of code can have for and addition logic.

Exercise

Now try changing the following function to a lambda.
def example4(x):
if x % 2 == 0:
return "even"
else:
return "odd"
Have a nice day!
為什麼會看到廣告
76會員
96內容數
將 CNN, BBC 等國際知名新聞平台翻譯成中文,協助國人快速掌握國際新聞脈絡。讓知識不限於國內大小事,而能放眼國際。
留言0
查看全部
發表第一個留言支持創作者!
從 Google News 追蹤更多 vocus 的最新精選內容