Core Python Programming Language : Page 477
Anonymous Functions and lambda
Python allows one to create anonymous functions using the lambda keyword. They are "anonymous"
because they are not declared in the standard manner, i.e., using the def statement. (Unless assigned
to a local variable, such objects do not create a name in any namespace either.) However, as functions,
they may also have arguments. An entire lambda "statement" represents an expression, and the body of
that expression must also be given on the same line as the declaration. We now present the syntax for
anonymous functions:
lambda [arg1[, arg2, ... argN]]: expression
Arguments are optional, and if used, are usually part of the expression as well.
Core Note: lambda expression returns callable function object
Calling lambda with an appropriate expression yields a function object
that can be used like any other function. They can be passed to other
functions, aliased with additional references, be members of container
objects, and as callable objects, be invoked (with any arguments, if
necessary). When called, these objects will yield a result equivalent to
the same expression if given the same arguments. They are
indistinguishable from functions that return the evaluation of an
equivalent expression.
One final word on lambda: Although it appears that lambda is a one-line version of a function, it is not
equivalent to an "inline" statement in C++, whose purpose is bypassing function stack allocation during
invocation for performance reasons. A lambda expression works just like a function, creating a frame
object when called.
11.7.2. Built-in Functions: apply(), filter(), map(), reduce()
In this section, we will look at the apply(), filter(), map(), and reduce() built-in functions as well as
give some examples to show how they can be used. These functions provide the functional programming
features found in Python. A summary of these functions is given in Table 11.2. All take a function object
to somehow invoke.
example:
#lambda默认参数与或变参数 >>> lfun=lambda x,y=10,*z: x+y+sum(z) >>> lfun(1) 11 >>> lfun(1,2) 3 >>> lfun(1,2,3) 6 >>> lfun(1,2,3,4,5) 15
#apply:应用方法 >>> apply(lambda x:x*2, [1]) 2 >>> apply(lambda x,y,z:x+y+z,[1,2,3]) 6 #filter:过滤序列 >>> l [24, 32, 41, 12, 22, 45, 50, 30, 44] >>> filter(lambda x:x%2 , l) [41, 45] #list单个序列做参数 >>> list1 = [49, 65, 82, 24, 44, 90, 100, 61, 88] >>> map(lambda x: x/2,list1) [24, 32, 41, 12, 22, 45, 50, 30, 44] #map多个序列做参数 >>> map(lambda x,y,z:x+y+z,[1,2,3],[10,20,30],[100,200,300]) [111, 222, 333] >>> zip([1,2,3],[10,20,30],[100,200,300]) [(1, 10, 100), (2, 20, 200), (3, 30, 300)] >>> map(None,[1,2,3],[10,20,30],[100,200,300]) [(1, 10, 100), (2, 20, 200), (3, 30, 300)] #reduce使用 >>> reduce(lambda x,y:x + y, [1,2,3,4,5]) 15 >>> reduce(lambda x,y:x + y, '12345') '12345' >>> reduce(lambda x,y:x + y, ('1','2','3','4','5')) '12345' >>> reduce(lambda x,y:x + y, (1,2,3,4,5)) 15