[Python 入门] Lambda 表达式

[Python 入门] Lambda 表达式

Lambda 表达式是一个会返回 一些格式数据 的 匿名函数

Lambda 表达式语法如下:

lambda parameters: expressions

i.e.

  1. double = lambda num : num * 2

  2. concat_first_letter = lambda a, b, c: a[0] + b[0] + c[0]

    concat_first_letter("World", "Wide", "Web") => WWW

Lambda 表达式必须在一行内写完,因此更加适合一些较短、能在一行内写完的函数。

如果在 Lambda 表达式中使用条件逻辑,则必须使用完整的 if-else,单独使用 if 会导致报错:

func = lambda num: "natural number" if num >= 0 else "negative number"

func(0) # 'natural number'

my_func = lambda num: "natural number" if num >= 0 # SyntaxError: invalid syntax

使用 Lambda 表达式的好处在于,可以将函数作为参数传给另外一个函数。

Lambda 表达式作为参数

以加乘为例,使用非 Lambda 的写法为:

def add(n1, n2):
    return n1 + n2

def multiply(n1, n2):
    return n1 * n2

def calculator(operation, n1, n2):
    return operation(n1, n2)

calculator(multiply, 10, 20) # 200

calculator(add, 10, 20) # 30

使用 Lambda 表达式的写法为:

def calculator(operation, n1, n2):
    return operation(n1, n2)  # Using the 'operation' argument as a function

calculator(lambda n1, n2: n1 * n2, 10, 20) # 200
calculator(lambda n1, n2: n1 + n2, 10, 20) # 30

同样的结果使用 Lambda 表达式会更加的简练,这也是 Lambda 表达式的初衷。

来自 Python 官方文档 - Why can’t lambda expressions contain statements?

Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you’re too lazy to define a function.

Python 中 Lambda 的设计初衷就是为了偷懒。

Lambda 表达式在列表中的应用:

num_list = [0, 1, 2, 3, 4, 5]

list(map(lambda n: n ** 2, num_list)) # [0, 1, 4, 9, 16, 25]

list(filter(lambda n: n > 0, num_list)) # [1, 2, 3, 4, 5]

猜你喜欢

转载自blog.csdn.net/weixin_42938619/article/details/120867959
今日推荐