程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Detailed explanation of Python lambda function usage]

編輯:Python

Python lambda() Function can simplify the program , We can lambda An expression is a simplified way to write a function , It can determine the output value according to the input value .

Usually Python When defining a function, you need to give the function name , however lambda The function name is not required , So we call it lambda Is an expression of anonymous functions . The syntax is as follows .

lambda parameter list , … : Expression where the colon before the expression “:” Don't omit , And can't use return sentence . for example , Transfer mathematical functions f(x)=3x-1 It's written in lambda expression ,Python The code is as follows :

result = lambda x : 3*x-1 #lambda() function
print(result(3)) # Output value 8

in other words “:” On the left is the parameter , On the right are expressions or blocks . For the purposes of this example ,“:” On the right is the expression 3*x-1, The number of parameters on the left is 1.

that Python Custom functions and lambda() What's the difference between functions ? Here is a simple example to illustrate ,Python The code is as follows :

def formula(x, y): # Custom function
return 3*x+2*y
formula = lambda x, y : 3*x+2*y # Express lambda There are two parameters
print(formula (5,10)) # Pass in two values to let lambda() Functions do operations , Output value 35

The above program code uses custom functions and lambda() Functions in two ways , We can observe that custom functions are similar to lambda() Functions have the following differences :

  • The function body of a custom function can have multiple lines of statements , however lambda() A function can only have one line of expression .
  • The custom function has a name , but lambda() Function has no name ,lambda() The function must specify a variable to store the result of the operation .
  • The result of the custom function is in return Statement returns ,lambda() Function assigns the result to the specified variable .
  • lambda() Function must be named as a variable ( In the example above formula Variable ) To call , Pass in parameters according to their definitions .

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved