Python supports an interesting syntax that allows you to quickly define the minimum function for a single line. These functions, called Lambda, are borrowed from Lisp and can be used wherever functions are needed.
Lambda's syntax is often confusing, what is lambda, why use lambda, is it necessary to use lambda?
>>> def f (x): ... Return x+2...>>> F (1) 3>>> f = lambda x:x+2>>> f (1) 3>>> (lambda x:x+2) (1) 3
Python def and Python Lambda have similarities and different points.
Similarities: The two very important similarities are that you can define a fixed method or a process that is called by a provider, such as a method that defines a variable plus 2 in the example above. The result of the output is 3, if you want to complete some fixed process, the above several you can choose arbitrarily.
The above is the same point, then there are those different points?
Their main difference is that Python def is a statement and Python lambda is an expression. Lambda simplifies the writing of function definitions, making the code more concise. But the use of functions is more intuitive and easy to understand.
Python inside statements can be nested, such as you need to define a method according to a condition, it can only use def. You will get an error with lambda.
>>> if a==1: ... def info (): ... print ' 1 ' ... else: ... Def info2 (): ... print ' Info2 '
And sometimes when you need to operate in a Python expression, you need to use the expression nesting, this time Python def can not get the results you want, it can only use Python lambda, the following example:
The most frequently occurring letter of the output E string:
>>> str= ' www.linuxeye.com linuxeye.com ' >>> L = ([(I,str.count (i)) for I in Set (str)]) [(' ", 1), (' C ', 2) , (' E ', 4), (' I ', 2), (' m ', 2), (' L ', 2), (' O ', 2), (' N ', 2), (' U ', 2), (' W ', 3), (' Y ', 2), (' X ', 2), ('. ', 3)]>>> ; L.sort (key = lambda K:k[1],reverse = True) >>> print L[0][0]e