This article mainly introduces special functions in Python. it mainly introduces four functions: 1 filter function filter2 ING and Combiner function mapredu137modifier @ 4 anonymous function lamda. For more information, see
The following content mainly includes the needle filter function, map and merge function, map/reduce, decorator @, and anonymous function lamda. the specific content is as follows:
1. filter function
Definition: the filter function is equivalent to a filter. Call a Boolean function bool_func to iterate over the elements in each list. return a sequence of elements that make bool_func return true.
The code is as follows:
A = [0, 1, 2, 3, 4, 5, 6, 7]
B = filter (None,)
Print B
Output result: [1, 2, 3, 4, 5, 6, 7]
Back to top
2. map and merge functions map/reduce
The map and reduce mentioned here are Python built-in functions, not the Goggle MapReduce architecture.
2.1 map functions
Map function format: map (func, seq1 [, seq2...])
In Python functional programming, the map () function acts func on every element in the list and returns the value with a list. If func is None, it serves as a zip () function.
When the list has only one, the map function works as a schematic:
For example, convert all the elements in the list to None.
The code is as follows:
Map (lambda x: None, [1, 2, 4])
Output: [None, None].
When there are multiple lists, the map () function works as a schematic:
That is to say, elements in the same position of each seq get a return value after executing a multi-element func function. these return values are placed in a result list.
The following example shows the product of the elements corresponding to two lists. as you can imagine, this is a situation that may often occur. if map is not used, a for loop is used, execute this function at each position in sequence.
The code is as follows:
Print map (lambda x, y: x * y, [1, 2, 3], [4, 5, 6]) # [4, 10, 18]
The preceding example shows that the returned value is a value. It can also be a tuples. The following code not only achieves multiplication, but also implements addition, and puts the product and in a tuple.
The code is as follows:
Print map (lambda x, y: (x * y, x + y), [1, 2, 3], [4, 5, 6]) # [(4, 5), (10, 7), (18, 9)]
In addition, the above-mentioned func is None, which aims to merge multiple elements in the same position of the list into a single tuple. now we have a dedicated function zip ().
The code is as follows:
Print map (None, [1, 2, 3], [4, 5, 6]) # [(1, 4), (2, 5), (3, 6)]
Print zip ([1, 2, 3], [4, 5, 6]) # [(1, 4), (2, 5), (3, 6)]
Note: the map function cannot be executed for multiple seq with different lengths, and a type error occurs.
2.2 reduce function
Reduce function format: reduce (func, seq [, init]).
The reduce function is a simplification. it is a process in which the result of the last iteration is the init element for the first iteration. if there is no init, it is the first element of seq) execute a binary func function together with the next element. In the reduce function, init is optional. if used, it is used as the first element of the first iteration.
To put it simply, you can use this visualized expression to describe:
The code is as follows:
Reduce (func, [1, 2]) = func (1, 2), 3)
The working principle of the reduce function is as follows:
For example, factorial is a common mathematical method. Python does not provide a built-in factorial function. we can use reduce to implement a factorial code.
The code is as follows:
N = 5
Print reduce (lambda x, y: x * y, range (1, n + 1) #120
So what if we want to get the 2x factorial value? In this case, the optional parameter init can be used.
The code is as follows:
M = 2
N = 5
Print reduce (lambda x, y: x * y, range (1, n + 1), m) #240
Back to top
3. decorator @
3.1 What is a decorator (function )?
Definition: The decorator is a function used to wrap the function. it is used to modify the original function, assign it to the original identifier, and permanently remove the reference of the original function.
3.2 decorator usage
Here is an example of a simple decorator:
The code is as follows:
#-*-Coding: UTF-8 -*-
Import time
Def foo ():
Print 'in foo ()'
# Define a timer, input one, and return another method with the timer function attached
The code is as follows:
Def timeit (func ):
# Define an embedded packaging function to pack the input function with the timing function
The code is as follows:
Def wrapper ():
Start = time. clock ()
Func ()
End = time. clock ()
Print 'used: ', end-start
# Return the packaged function
The code is as follows:
Return wrapper
Foo = timeit (foo)
Foo ()
Output:
The code is as follows:
In foo ()
Used: 2.38917518359e-05
Python provides a @ symbol syntax sugar for the decorator to simplify the above code. they play the same role. The code above can also be written as this (the decoration device proprietary writing method, pay attention to the symbol "@"):
The code is as follows:
#-*-Coding: UTF-8 -*-
Import time
# Define a timer, input one, and return another method with the timer function attached
The code is as follows:
Def timeit (func ):
# Define an embedded packaging function to pack the input function with the timing function
The code is as follows:
Def wrapper ():
Start = time. clock ()
Func ()
End = time. clock ()
Print 'used: ', end-start
# Return the packaged function
The code is as follows:
Return wrapper
@ Timeit
Def foo ():
Print 'in foo ()'
# Foo = timeit (foo)
Foo ()
In fact, we can refer to the decoration device name for its understanding. There are three main points:
1) first, the decorator uses the function name as the input (which indicates that the decorator is a high-level function );
2) process the original function using the internal syntax of the decorator and return the result;
3) the original function is assigned a new function through the decorator. The new function overwrites the original function, and then calls the original function in the future will play a new role.
To put it bluntly, the decorator is equivalent to a function processing factory, which can re-process functions and assign new functions.
Nest of the decorator:
#!/usr/bin/python# -*- coding: utf-8 -*-def makebold(fn): def wrapped(): return "" + fn() + "" return wrappeddef makeitalic(fn): def wrapped(): return "" + fn() + "" return wrapped@makebold@makeitalicdef hello(): return "hello world"print hello()
Output result:
Hello world
Why is this result?
1) first, the hello function is decorated by the makeitalic function and becomes the result.Hello world
2) Then, after the decoration of the makebold function, it becomesHello worldThis is easy to understand.
Back to top
4. Anonymous function lamda
4.1 What is an anonymous function?
In Python, there are two types of functions: def definition and lambda function.
Definition: a function without a function name. Lambda expressions are a special type of defined functions in Python. they can be used to define an anonymous function. Different from other languages, the function body of the Lambda expression of Python can only have one unique statement, that is, the return value expression statement.
4.2 Anonymous functions
Lambda is generally in the form of a keyword lambda, followed by one or more parameters followed by a colon followed by an expression:
The code is as follows:
Lambda argument1 argument2...: expression using arguments
Lambda is an expression rather than a statement.
A lambda subject is a single expression rather than a code block.
For a simple example, if the sum of two numbers is required, use a common function or an anonymous function as follows:
1) common function: def func (x, y): return x + y
2) anonymous functions: lambda x, y: x + y
For another example, a list must contain only three elements.
1) General method:
The code is as follows:
L1 = [1, 2, 3, 4, 5]
L2 = []
For I in L1:
If I> 3:
L2.append (I)
2) functional programming implementation: use filter to give it a judgment condition.
The code is as follows:
Def func (x): return x> 3
Filter (func, [1, 2, 3, 4, 5])
3) using anonymous functions is more streamlined, and one line is enough:
The code is as follows:
Filter (lambda x: x> 3, [1, 2, 3, 4, 5])
Conclusion: lambda is generally used in functional programming with simple code. it is often used in combination with reduce, filter, and other functions. In addition, there cannot be return in lambda functions. In fact, ":" is followed by the return value.
Why use anonymous functions?
1) when using Python to write some execution scripts, using lambda can save the process of defining functions and simplify the code.
2) for some abstract functions that will not be reused elsewhere, it is also difficult to give a name to the function. you do not need to consider naming when using lambda.
3) use lambda to make the code easier to understand in some cases.
The above is a detailed description of special functions in Python, and I hope to help you.