Home > Article > Backend Development > An example to explain the use of Python's lambda statement to declare anonymous functions
The so-called anonymous function means that there is no need to define a function, it can be used like an expression, and there is no need for a function name (many times the name bothers me). Some simple functions are simplified. For example
I need two A function that adds integers is usually defined like this
def add(x, y): return x + y
It completes the function I need very well, but now I need a function that adds numbers and strings
def addstr(x, y): return x + str(y)
Once again completed my needs, but I suddenly need the function of subtracting and dividing two integers, so the function has to be written down all the time, but using lambda anonymous functions can be used directly
# 相加的实现 f = lambda x, y: x + y f_str = lambda x, y: x + str(y)
Simplifies the operation to make the function simpler, but one disadvantage is poor maintainability. It is not recommended when complex functions are required
lambda [arg1[, arg2, ... argN]]: expression
The following example illustrates the use of lambda statements (no parameters) ).
Python anonymous function lambda example (no parameters) Python
# 使用def定义函数的方法 def true(): return True #等价的lambda表达式 >>> lambda :True <function <lambda> at 0x0000000001E42518> # 保留lambda对象到变量中,以便随时调用 >>> true = lambda :True >>> true() True # 使用def定义函数的方法 def true(): return True #等价的lambda表达式 >>> lambda :True <function <lambda> at 0x0000000001E42518> # 保留lambda对象到变量中,以便随时调用 >>> true = lambda :True >>> true() True
The following is another example with parameters.
Python anonymous function lambda example (including parameters) Python
# 使用def定义的函数 def add( x, y ): return x + y # 使用lambda的表达式 lambda x, y: x + y # lambda也允许有默认值和使用变长参数 lambda x, y = 2: x + y lambda *z: z # 调用lambda函数 >>> a = lambda x, y: x + y >>> a( 1, 3 ) 4 >>> b = lambda x, y = 2: x + y >>> b( 1 ) 3 >>> b( 1, 3 ) 4 >>> c = lambda *z: z >>> c( 10, 'test') (10, 'test') # 使用def定义的函数 def add( x, y ): return x + y # 使用lambda的表达式 lambda x, y: x + y # lambda也允许有默认值和使用变长参数 lambda x, y = 2: x + y lambda *z: z # 调用lambda函数 >>> a = lambda x, y: x + y >>> a( 1, 3 ) 4 >>> b = lambda x, y = 2: x + y >>> b( 1 ) 3 >>> b( 1, 3 ) 4 >>> c = lambda *z: z >>> c( 10, 'test') (10, 'test')
Does the code look more concise without losing readability?
For more examples to explain the usage of Python’s lambda statement to declare anonymous functions, please pay attention to the PHP Chinese website for related articles!