Python_Lamdbda表达式

4.7.5. 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')]

 

关于Lambda表达式,今天在练习Python基础时看到第二个例子时卡壳了。原地址:https://docs.python.org/3/tutorial/controlflow.html#if-statements

pair就是迭代列表中每个元素,例子中即每个元组,pair[1]就是每个元组中的第二个元素'one','two','three','four’。实现的功能就是将列表按字符串的首字母进行排序。

posted @ 2017-03-02 13:35  雨注金池  Views(1131)  Comments(0)    收藏  举报