Normal def 定义函数和 Lambda 之间的区别
在本文中,我们将讨论Python中普通的 def 定义函数和 lambda 之间的区别。
def关键字
在Python中,def 定义的函数因其简单性而被广泛使用。 def 定义的函数如果没有显式返回,则不会返回任何内容,而 lambda函数确实返回一个对象。 def 函数必须在命名空间中声明。 def 函数可以执行任何Python任务,包括多个条件、任何级别的嵌套条件或循环、打印、导入库、引发异常等。
示例:
Python3
# Define function to calculate cube root
# using def keyword
def calculate_cube_root(x):
return x**(1/3)
# Call the def function to calculate cube
# root and print it
print(calculate_cube_root(27))
# Define function to check if language is present in
# language list using def keyword
languages = ['Sanskrut', 'English', 'French', 'German']
def check_language(x):
if x in languages:
return True
return False
# Call the def function to check if keyword 'English'
# is present in the languages list and print it
print(check_language('English'))
Python3
# Define function using lambda for cube root
cube_root= lambda x: x**(1/3)
# Call the lambda function
print(cube_root(27))
languages = ['Sanskrut', 'English', 'French', 'German']
# Define function using lambda
l_check_language = lambda x: True if x in languages else False
# Call the lambda function
print(l_check_language('Sanskrut'))
输出:
3.0
True
Lambda 关键字
lambda 函数可以在命名空间中没有任何声明的情况下使用。上面定义的 lambda 函数类似于单行函数。这些函数不像 def 定义的函数那样有括号,而是在 lambda 关键字之后接受参数,如上所示。没有明确定义 return 关键字,因为 lambda函数默认返回一个对象。
示例:
Python3
# Define function using lambda for cube root
cube_root= lambda x: x**(1/3)
# Call the lambda function
print(cube_root(27))
languages = ['Sanskrut', 'English', 'French', 'German']
# Define function using lambda
l_check_language = lambda x: True if x in languages else False
# Call the lambda function
print(l_check_language('Sanskrut'))
输出:
3.0
True
def 和 Lambda 的区别表
def defined functions | lambda functions |
---|---|
Easy to interpret | Interpretation might be tricky |
Can consists of any number of execution statements inside the function definition | The limited operation can be performed using lambda functions |
To return an object from the function, return should be explicitly defined | No need of using the return statement |
Execution time is relatively slower for the same operation performed using lambda functions | Execution time of the program is fast for the same operation |
Defined using the keyword def and holds a function name in the local namespace | Defined using the keyword lambda and does not compulsorily hold a function name in the local namespace |