Lambda functions and sorting in Python

Source: Internet
Author: User

A few days ago, I saw the Python code for a 1000 factorial line.

Python code

 
 
  1. print   reduce(lambda   x,y:x*y,   range(1,   1001))   

The python code is simplified and compact, so the code is analyzed in a simple way.

Reduce and range are built-in functions of Python.

Range1, 1001) indicates generating a List of consecutive integers from 1 to 1000 ).

ReducefunctionA, iterableB), functionA is a function that requires two variables and returns a value. IterableB is an iterative variable, such as List. The reduce function transmits the elements in B from left to right to function A, and then replaces the input parameters with the results returned by function A. After Repeated execution, B can be reduced to A single value. Here, it is to pass the continuous integer list from 1 to 1000 into the lambda function and replace the number in the list with the product of two numbers. The actual calculation process is :(... (1 × 2) × 3) × 4) ×... * 1000). The final result is the factorial of 1000.

The following describes the lambda functions.

Lambda functions are the smallest function that quickly defines a single row. They are borrowed from Lisp and can be used wherever functions are needed. The following example compares the definition of a traditional function with a lambda function:

 
 
  1. >>> def f(x,y):   
  2. ...     return x*y   
  3. ...       
  4. >>> f(2,3)   
  5.  
  6. >>> g = lambda x,y: x*y   
  7. >>> g(2,3)  

As you can see, the results of the two functions are the same. For functions that implement simple functions, using lambda functions for definition is more streamlined and flexible. You can also assign a function to a variable directly, the variable name is used to represent the function name.

In fact, in many cases, lambda functions do not need to assign values to a variable, such as the process of finding a factorial in the previous article ).

Precautions for using lambda functions:

Lambda functions can receive any number of parameters (including optional parameters) and return the value of a single expression.

Lambda functions cannot contain commands and cannot contain more than one expression.

The following describes how to use the lambda function to implement custom sorting.

 
 
  1. class People:  
  2.     age=0 
  3.     gender='male' 
  4.  
  5.     def __init__(self, age, gender):    
  6.         self.age = age    
  7.         self.gender = gender  
  8.     def toString(self):  
  9.         return 'Age:'+str(self.age)+'\tGender:'+self.gender  
  10.  
  11. List=[People(21,'male'),People(20,'famale'),People(34,'male'),People(19,'famale')]  
  12. print 'Befor sort:' 
  13. for p in List:  
  14.     print p.toString()  
  15.  
  16. List.sort(lambda p1,p2:cmp(p1.age,p2.age))  
  17. print '\nAfter ascending sort:' 
  18. for p in List:  
  19.     print p.toString()  
  20.  
  21. List.sort(lambda p1,p2:-cmp(p1.age,p2.age))  
  22. print '\nAfter descending sort:' 
  23. for p in List:  
  24.     print p.toString() 

The code above defines a People class and uses the lambda function to sort the list of People objects in ascending and descending order according to the age of People. The running result is as follows:

 
 
  1. Befor sort:   
  2. Age:21 Gender:male   
  3. Age:20 Gender:famale   
  4. Age:34 Gender:male   
  5. Age:19 Gender:famale   
  6.  
  7. After ascending sort:   
  8. Age:19 Gender:famale   
  9. Age:20 Gender:famale   
  10. Age:21 Gender:male   
  11. Age:34 Gender:male   
  12.  
  13. After descending sort:   
  14. Age:34 Gender:male   
  15. Age:21 Gender:male   
  16. Age:20 Gender:famale   
  17. Age:19 Gender:famale  

References:

Go deep Into Python: Dive Into Python Chinese Version

Http://docs.python.org/lib/built-in-funcs.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.