Python's lambda functions and sorting2010-03-02 15:02 2809 People read comments (0) favorite reports Lambdapythonlistlispclass work
Directory (?) [+]
A few days ago I saw a line of Python code that asks for 1000 factorial:
Print reduce ( lambda x , y : x * y , range ( 1 , 1001 ))
The simplicity and compactness of the Python code makes it easy to analyze the code.
Both the reduce and range are built-in functions of Python.
Range (1,1001) is a list of consecutive integers that generate 1 to 1000.
Reduce (Functiona,iterableb), Functiona is a function that requires two variables, and returns a value. Iterableb is an iterative variable, such as list. The reduce function passes the elements in B from left to right into function A, and then replaces the incoming parameters with the result returned by function A, and repeatedly executes the b reduce to a single value. Here, the list of consecutive integers from 1 to 1000 is passed into the lambda function and the number in the list is replaced by a two-number product, the actual calculation process is: (...) (1x2) x3) (x4) x...x1000), the final result is the factorial of 1000.
Here's a look at the lambda function.
A lambda function is a minimal function that quickly defines a single line, borrowed from Lisp and can be used wherever a function is needed. The following example compares the definition of a traditional function with a lambda function:
1>>>DefF(X, y):
2...ReturnX*Y
3...
4>>>f ( 2,3 5 6 
6 >>> g = lambda x ,y : x * Y 
7 >>> g 2,3 8 < Span class= "_MF" >6
As you can see, the two functions get the same results, and for functions that implement simple functions, the use of a lambda function to define more streamlined and flexible, you can also directly assign a function to a variable, the variable name to represent the function name.
In fact, lambda functions often do not need to be assigned to a variable (such as the process of seeking factorial in the preceding article).
There are a few things to note about using lambda functions:
A lambda function can receive any number of arguments (including optional parameters) and return the value of a single expression.
A lambda function cannot contain commands and cannot contain more than one expression.
01ClassPeople:
02Age=0
03Gender=' Male '
04
05Def__init__(Self,Age,Gender):
06Self.Age=Age
07Self.Gender=Gender
08DefTostring(Self):
09Return' Age: '+Str(Self.Age)+‘/tGender: '+Self.Gender
10
11List=[People(21st,' Male '),People(20,' Famale '),People(34,' Male '),People(19,' Famale ')]
12Print' Befor sort: '
13ForPInchList:
14PrintP.Tostring()
15
16List.Sort(LambdaP1,P2:Cmp(P1.Age,P2.Age))
17Print‘/nAfter ascending sort: '
18ForPInchList:
19PrintP.Tostring()
20
21stList.Sort(LambdaP1,P2:-Cmp(P1. age , p2 . age 22 < Span class= "_k" >print " /n After descending sort: '
23 for p in List < Span class= "_p" >:&NBSP;
24 print p . Tostring ()
The above code defines a people class and, through a lambda function, implements a list of objects containing people classes in ascending and descending order, according to the age of people. The results of the operation are as follows:
Befor Sort:
Age:21 Gender:male
Age:20 Gender:famale
Age:34 Gender:male
Age:19 Gender:famale
After ascending sort:
Age:19 Gender:famale
Age:20 Gender:famale
Age:21 Gender:male
Age:34 Gender:male
After descending sort:
Age:34 Gender:male
Age:21 Gender:male
Age:20 Gender:famale
Age:19 Gender:famale
lambda
Statements are used to create new function objects, and they are returned at run time.
Example 15.2 using lambda form
#!/usr/bin/python
# Filename: lambda.py
def
make_repeater
(n):
return lambda
s: s*n
twice = make_repeater(
2
)
print
twice(
‘word‘
)
print
twice(
5
)
(source file: code/lambda.py)
Output
$ python lambda.py
wordword
10
How it works
Here, we use the make_repeater
function to create a new function object at run time and return it. lambda
statement to create a function object. Essentially, lambda
a parameter is required, followed only by a single expression as the body of the function, and the value of the expression is returned by the new function. Note that even statements cannot be used in print
lambda form, only expressions are used.
Python's lambda functions and sorting