[Python] Some of the special functions in Python

Source: Internet
Author: User

1. Filtering function Filter

  definition : The function of the filter function is equivalent to a filter. Call a Boolean function Bool_func to iterate through the elements in each list, and return a sequence of elements that enable Bool_func to return a value of true.

a=[0,1,2,3,4,5,6,7]b=filter (None, a)print b

  Output results: [1, 2, 3, 4, 5, 6, 7]

2. Mapping and merging functions Map/reduce

The map and reduce in this case are Python's built-in functions, not Goggle's MapReduce schema.

2.1 Map function

the format of the map function: Map (func, seq1[, seq2 ...])

The map () function in Python's functional programming is to act on each element of the list with Func and give the return value with a list. If Func is none, the action is equivalent to a zip () function.

When the list is only one, the map function works as a schematic:

For a simple example, convert all the elements in the list to none.

Map (Lambda

 Output: [None,none,none,none].

When the list has multiple, the map () function works as a schematic:

That is, each SEQ element in the same position is given a return value after executing a multivariate Func function, and these return values are placed in a list of results.

The following example is for the product of the corresponding element of the two list, which can be imagined as a condition that is likely to occur frequently, and if it is not a map, use a For loop, and then execute the function for each position in turn.

Print Lambda x, y:x * y, [1, 2, 3], [4, 5, 6])  #  [4, ten,]

The above is a case where the return value is a value, and it can actually be a tuple. The following code does not only implement multiplication, it also implements addition, and puts the product and sum in a single tuple.

Print Lambda x, y: (x * y, x + y), [1, 2, 3], [4, 5, 6])  #  [(4, 5), (, 7), (9)]

And that's what it says. The func is None , and its purpose is to merge elements of multiple lists in the same position into a tuple, which now has a dedicated function zip() .

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: multiple seq of different lengths is unable to execute the map function, and a type error occurs.

2.2 Reduce function

Reduce function Format: Reduce (func, seq[, Init]).

The reduce function is a simplification, which is a process in which the last iteration result (the element with the first init, such as the first element of the SEQ without init), executes a two-dollar func function with the next element, each iteration. In the reduce function, init is optional and, if used, is used as the first element of the first iteration.

In simple terms, you can use a visual formula to illustrate:

Reduce (func, [i]) =func (func), 3)

The reduce function works as follows:

For example, factorial is a common mathematical method, and Python does not give a factorial built-in function, and we can use reduce to implement a factorial code.

n = 5print reduce (lambda x, y:x * y, Range (1, n + 1))  #  

So, what if we want to get twice times the factorial value? This allows you to use the optional parameters of init.

m = 2= 5printlambda x, y:x * y, Range (1, n + 1), M)  #  
3. Adorner @

3.1 What is an adorner (function)?

  definition : An adorner is a function that wraps a function, which modifies the original function, assigns it to the original identifier, and permanently loses the reference to the original function.

3.2 Use of adorners

Let's start with an example of a simple decorator:

#-*-coding:utf-8-*-Import Timedeffoo ():Print 'In foo ()'#Define a timer, pass in one, and return another method with the timer feature attacheddefTimeit (func):#define an inline wrapper function that adds a timing function to the incoming function    defwrapper (): Start=Time.clock () func () End=Time.clock ()Print 'used:', End-Start#returns the Wrapped function    returnWrapperfoo=Timeit (foo) foo ()

Output:

in 2.38917518359e-05

Python provides an @-symbol syntax sugar specifically for adorners to simplify the code above, and they work the same way. The above code can also be written like this (the adorner's proprietary notation, note the symbol "@"):

#-*-coding:utf-8-*-Import Time#Define a timer, pass in one, and return another method with the timer feature attacheddefTimeit (func):#define an inline wrapper function that adds a timing function to the incoming function    defwrapper (): Start=Time.clock () func () End=Time.clock ()Print 'used:', End-Start#returns the Wrapped function    returnwrapper@timeit deffoo ():Print 'In foo ()'#foo = Timeit (foo)Foo ()

  In fact, the understanding of the adorner, we can according to its name, mainly has three points:

1) The first feature of the adorner is that it takes the function name as input (which means that the adorner is a higher-order function);

2) The original function is processed by the internal syntax of the adorner, and then returned;

3) The original function through the adorner is given a new function, the new function overrides the original function, and then call the original function, will play a new role.

To put it bluntly, the adorner is equivalent to a function factory, which can be re-processed to give its new functions.

  Nesting of adorners:

#!/usr/bin/python#-*-coding:utf-8-*-defMakebold (FN):defwrapped ():return "<b>"+ fn () +"</b>"    returnWrappeddefmakeitalic (FN):defwrapped ():return "<i>"+ fn () +"</i>"    returnWrapped@makebold@makeitalicdefHello ():return "Hello World"PrintHello ()

Output Result:

<b><i>hello world</i></b>

Why is this result?
1) First the Hello function is decorated by the Makeitalic function and becomes the result <i>hello world</i>
2) and then through the decoration of the Makebold function, into the <b><i>hello World</i></b>, which is easy to understand.

4. anonymous function Lamda

4.1 What is an anonymous function?

  in the Python, There are two kinds of functions , one is def definition , and one is a lambda function.

  definition : As the name implies, a function without a function name. A lambda expression is a special type of defined function in Python that allows you to define an anonymous function. Unlike other languages, the function body of a Python lambda expression can have only one statement, which is the return value expression statement.

4.2 Usage of anonymous functions

The general form of a lambda is the keyword lambda, followed by one or more parameters, followed by a colon, followed by an expression:

Lambda argument1 argument2 ...: expression using arguments

A lambda is an expression, not a statement.

  A lambda body is a single expression, not a block of code.

  To give a simple example, if the sum of two numbers is required, use a normal function or an anonymous function as follows:
1) normal function: def func (x, y): Return x+y
2) anonymous function: Lambda x,y:x+y

One more example: for a list, the requirement can only contain elements greater than 3.

1) General Method:

L1 = [1,2,3,4,5= [ ] for in L1:    if i>3:        l2.append (i)

  2) Functional Programming Implementation: the use of filter, give it a judgment condition can

def return x>3filter (func,[1,2,3,4,5])

  3) The use of anonymous functions, it is more streamlined, one line can be:

Filter (Lambda x:x>3,[1,2,3,4,5])

Summary: from which you can see   , Lambda is generally used for functional programming, code simplicity, and often used in conjunction with functions such as reduce,filter. In addition, there can be no return in the lambda function, in fact ":" is followed by the return value.

  Why use anonymous functions?

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 problems.

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

[Python] Some of the special functions in Python

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.