Python Lambda and Python def

Source: Internet
Author: User

1. Python Lambda and Python def Difference analysis

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?

?
12345678910 >>> 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.

?
123456 >>> 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 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:

?
123456 >>> 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

2. Python's Lambda anonymous function

(1) When using Python to write some execution scripts, using lambda eliminates the process of defining a function and makes the code more streamlined.

(2) for some abstract functions that are not reused elsewhere, sometimes it is difficult to name a function, and using lambda does not have to consider naming the problem.

(3) Using lambda makes the code easier to understand at some point.

Lambda Basics
In a lambda statement, the colon is preceded by a parameter, which can have multiple, separated by commas, and a return value to the right of the colon. The lambda statement is actually built as a function object with the following code:

g = Lambda X:x**2print g<function <lambda> at 0x00afaaf0>

C#3.0 begins with a lambda expression, eliminating the hassle of using delegate. The lambda expression keyword in C # is => look at the following example, the code is as follows:

var array = new int[] {2, 3, 5, 7, 9};var result = array. Where (n = n > 3); [5, 6, 9]

C # uses extension methods to make the array object have a convenient way like where,sum. In Python, there are also several well-defined global functions that are easy to use, they are filter, map, reduce. The code is as follows:

>>> foo = [2, 9, 8, +, 27]>>>>>> print filter (lambda x:x% 3 = = 0, foo) [18, 9 , 27]>>>>>> print map (Lambda x:x * 2 + ten, foo) [+, +, +, si, si, +,, 64]>>> >>> print reduce (lambda x, y:x + y, foo) 139

Not lambda?
The map in the example above has the same function as the where extension method in C #, which is very simple and convenient. But does Python have to use lambda to make this simple? In the object traversal process, in fact Python for. In.. The IF syntax is already strong and is more readable than lambda. For example, the map above can be written in the following code:

print [x * 2 + ten for x in Foo]

It's very concise and easy to understand. The filter example can be written with the following code:

print [x for x in foo if x% 3 = = 0]

It's also easier to understand than a lambda way.

So, when to use lambda, when not to, need specific case specific analysis, as long as the expression of the intention clearly good. In general, if for: In.. If I can do that, I will not choose lambda.

Lambda broken?
In math teaching, lambda is often used, such as having a man who encounters such a problem. He wants to create an array of functions fs=[f0,..., F9] where FI (n) =i+n. Thus, a lambda function is defined with the following code:

FS = [(lambda n:i + N) for I in range (10)]

But, oddly enough, the code is as follows:

>>> Fs[3] (4) 13>>> Fs[4] (4) 13>>> fs[5] (4) 13

The results did not meet this man's expectations, the expected result should be, the code is as follows:

>>> Fs[3] (4) 7>>> Fs[4] (4) 8>>> fs[5] (4) 9

The problem is actually on the variable i. The code above is a simple, reduced version that does not use lambda, with the following code:

i = 1def FS (n): return n + iprint FS (1) # 2i = 2print FS (1) # 3

As you can see, the reason above is not expected is that I in Lambda uses a global variable outside of the anonymous function. Modify the code as follows:

FS = [(lambda n, i=i:i + N) for I in range (]>>> fs[3] (4) 7>>> Fs[4] (4) 8>>> fs[5] (4) 9

3. Python def function

In Python programming, for some programs that require repeated calls, you can use a function to define the basic form:

def function name (parameter 1, Parameter 2, ..., parameter n):

The EXECUTE statement function name is the name of the invocation, and the parameter is the passed-in parameter, which can be defined more or not.

?
1234567891011 # 例1:简单的函数使用# coding=gb2312# 定义函数def hello():  print ‘hello python!‘   # 调用函数    hello()  >>> hello python!

Functions can have parameters and return values, parameters will be left-to-right matching, parameters can be set default values, when the function is not given the corresponding parameters, will be assigned by default values.

?
1234567891011121314151617181920 # 例2:累加计算值# coding=gb2312# 定义函数def myadd(a=1,b=100):  result = 0  i = a  while i <= b:  # 默认值为1+2+3+……+100    result +=     i += 1  return result# 打印1+2+……+10    print myadd(1,10)print myadd()    # 使用默认参数1,100print myadd(50)   # a赋值50,b使用默认值  >>> 55>>> 5050>>> 3825

When the parameters of a Python function are passed, it is worth noting that when a parameter is passed in, the variable is treated as a temporary assignment to the parameter variable, and if the object is referenced.

?
12345678910111213141516 # 例3:# coding=gb2312def testpara(p1,p2):  p1 = 10  p2.append(‘hello‘)l = []   # 定义一数组对像a = 20# 给变量a赋值testpara(a,l) # 变量a与对象数组l作为参数传入print a   # 打印运行参数后的值for v in l: # 打印数组对象的成员  print v    >>> 20# 调用函数后a变量并未被复值>>> hello  # 而对象l数组则增加成员hello

Python Lambda and Python def

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.