Python supports an interesting syntax that allows you to quickly define the smallest function of a single line. These functions, called Lambda, are borrowed from Lisp and can be used wherever a function is needed.
The syntax of a lambda is often confusing, what is a lambda, and why is it necessary to use a 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 as well as different points.
Similarities: These two very important similarities are that you can define a fixed method or a process, a supply program to invoke, such as a method that defines a variable plus 2 in the example above. The output results are 3, and if you want to complete some fixed process, you can choose any of the above.
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. However, the use of the definition of functions is more intuitive and easy to understand.
Python statements can be nested, such as you need to define a method based on a condition, which can only be done with def. Use a lambda to make an error.
>>> if a==1:
... def info ():
... print ' 1 ' *5 ...
else: ... Def info2 ():
. print ' Info2 '
And sometimes when you need to operate in a Python expression, you need to use an expression nesting, and then Python def won't get the results you want, which can only be in Python lambda, as in the following example:
The output e string appears with the highest frequency of letters:
>>> 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