python: lambda expressions (anonymous functions)

Anonymous function study notes:

When we pass in functions, sometimes, we don't need to explicitly define the function, and it is more convenient to pass in the anonymous function directly.

In Python, there is limited support for anonymous functions. Taking a map()function as an example, when calculating f(x)=x2, in addition to defining a f(x)function, you can also directly pass in an anonymous function:

>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) [1, 4, 9, 16, 25, 36, 49, 64, 81] 

By comparison, it can be seen that the anonymous function lambda x: x * xis actually:

>>>def f(x): return x * x 

The keyword lambdarepresents an anonymous function, and the one before the colon xrepresents the function parameter.

Anonymous functions have a limitation, that is, there can only be one expression, no need to write return, the return value is the result of the expression.

There is an advantage to using anonymous functions, because functions don't have names, and you don't have to worry about function name collisions. In addition, an anonymous function is also a function object. You can also assign an anonymous function to a variable, and then use the variable to call the function:

>>> f = lambda x: x * x
>>> f
<function <lambda> at 0x101c6ef28> >>> f(5) 25 

Similarly, anonymous functions can also be returned as return values, for example:

>>>def build(x, y): return lambda: x * x + y * y


练习:用lambda表达式改写以下代码

def is_odd(n):
return n % 2 == 1

L = list(filter(is_odd, range(1, 20)))

 

#According to the writing method of map(), my code is rewritten as:

>>>list(map(lambda x:x%2==1,range(1,20)))

#The result is a boolean:
[True, False, True, False, True, False, True, False, True, False, True, False, True, False, True, False, True, False, True]

Therefore, the filter() function is added here  (the filter() function is used to filter the sequence, filter out the elements that do not meet the conditions, and return a new list of elements that meet the conditions.) :

 

>>> list(filter(lambda n:n%2==1, range(1, 20)))

#[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325218742&siteId=291194637