【原文】
4.8.6. Lambda Expressions
Small anonymous functions can be created with the lambda
keyword. This function returns the sum of its two arguments: lambda a, b: a+b
. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope:
>>>
>>> def make_incrementor(n): ... return lambda x: x + n ... >>> f = make_incrementor(42) >>> f(0) 42 >>> f(1) 43
The above example uses a lambda expression to return a function. Another use is to pass a small function as an argument:
>>>
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] >>> pairs.sort(key=lambda pair: pair[1]) >>> pairs [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
【译】
4.8.6.lambda 表达式
可以建立带有关键字lambda的小型匿名函数。这个函数返回两个参数的和:lambda a, b: a + b。只要被请求,Lambda函数就可以使用。它们在语法上仅限于单个表达式。语义上讲,它们仅仅是普通函数的语法糖。像嵌套函数定义一样,lambda函数可以引用容器中的变量:
上面的应用是用lambda表达式返回一个函数。另一种应用是将小函数作为参数传递。