lambda python
Python Lambda关键字 (Python lambda keyword)
lambda is a keyword (case-sensitive) in python, it is used to create an anonymous function that can accept any number of arguments but a single expression/statement.
lambda是python中的一个关键字(区分大小写),用于创建一个匿名函数,该函数可以接受除单个表达式/语句外的任意数量的参数。
Syntax of lambda keyword
lambda关键字的语法
function_name = lambda parameters_list : expression
Example:
例:
Input:
# lambda function to find power
power = lambda x,y : x**y
# calling function
result = power(10, 3)
print(result)
Output:
1000
Lambda关键字的Python示例 (Python examples of lambda keyword)
Example 1: Create a lambda function to find sum of 4 numbers.
示例1:创建一个lambda函数以查找4个数字的和。
# python code to demonstrate example of
# lambda keyword
# Create a lambda function to find sum of 4 numbers
# lambda function to add 4 numbers
addnumbers = lambda n1,n2,n3,n4 : n1+n2+n3+n4
# numbers
a = 10
b = 20
c = 30
d = 40
# printing the sum by calling lambda function
print("sum = ", addnumbers(a,b,c,d))
Output
输出量
sum = 100
Example 2: Create a lambda function to find a to the power b, where, a and b are the parameters.
实施例2:创建lambda函数查找到功率b,其中,a和b是参数。
# python code to demonstrate example of
# lambda keyword
# Create a lambda function to find a to the power b,
# where a and b are the parameters
# lambda function to find power
power = lambda x,y : x**y
a = 10 # base
b = 3 # power
# calling function
result = power(a,b)
# printing the result
print("power of ", a, " and ", b, " is = ", result)
Output
输出量
power of 10 and 3 is = 1000
翻译自: https://www.includehelp.com/python/lambda-keyword-with-example.aspx
lambda python