"Python" high-order features

Source: Internet
Author: User

Python advanced Features1, the derivation of the set formula
    • A list derivation that constructs a new list with an expression that can contain actions such as filtering, transformations, and so on.

Syntax: [Exp for item in collection if Codition]

    • A dictionary derivation that constructs a new list with an expression that can contain actions such as filtering, transformations, and so on.

Syntax: {KEY_EXP:VALUE_EXP for item in collection if Codition}

    • Set Deduction formula

Syntax: {EXP for item in collection if Codition}

    • Nested-List derivation

2. anonymous function lambda

    • No name of the function
    • Single statement composition
    • The result of the statement execution is the return value
    • Key functions that can be used as sort

Python high-order functions

1. Map/reduce function

    • Map (fun, LST), which functions the incoming function variable func to each element of the LST variable and returns the result as a new list

    • Reduce (func (x, y), lst), where Func must have two parameters. The result of each Func calculation continues and the next element of the sequence is calculated cumulatively.

LST = [A1, a2, A3, ..., an]

Reduce (func (x, y), lst) = Func (Func (func (A1, A2), A3), ..., an)

2. Filter function

    • Filter sequences
    • Filter (func, LST), which functions func on each element of the LST, and then determines whether the element is persisted or discarded, depending on whether the return value is true or false.

NumPy advanced functions 1, Np.nditer (): NumPy iterators

By default, the nditer array to iterate over is treated as a read-only object (read-only), in order to implement an array element that is worth modifying while iterating through the arrays, you must specify the op_flags=[' readwrite ' mode:

Np.nditer (A, op_flags=['readwrite'])

The basic iteration parameter flag=[' f_index '/' Mulit_index '], which outputs its own coordinates it.index/it.multi_index:

A = Np.arange (6). Reshape (2,3)" "Iterative Approach" "#single-Dimension iterationit = Np.nditer (A, flags=['F_index']) while  notit.finished:Print("%d <%s>"%(It[0], It.index)) It.iternext ()#0 <0>#1 <2>#2 <4>#3 <1>#4 <3>#5 <5>#Multidimensional iterationsit = Np.nditer (A, flags=['Multi_index']) while  notit.finished:Print("%d <%s>"%(It[0], It.multi_index)) It.iternext ()#0 < (0, 0) >#1 < (0, 1) >#2 < (0, 2) >#3 < (1, 0) >#4 < (1, 1) >#5 < (1, 2) >

Change the order of the iterations:

#Column order iterationsit = Np.nditer (A, flags=['F_index'], order='F') while  notit.finished:Print("%d <%s>"% (It[0], it.index), end=' | ') It.iternext ()#0 <0> | 3 <1> | 1 <2> | 4 <3> | 2 <4> | 5 <5> |#Row Order iterationsit = Np.nditer (A, flags=['F_index'], order='C') while  notit.finished:Print("%d <%s>"% (It[0], it.index), end=' | ') It.iternext ()#0 <0> | 1 <2> | 2 <4> | 3 <1> | 4 <3> | 5 <5> |

2. Ufunc operation

Ufunc is an abbreviation for the Universal function, which is a function that can operate on each element of an array. Many of the Ufunc functions built into the NumPy are implemented at the C language level, so they are computationally fast.

By combining the call of the standard Ufunc function, we can realize the array calculation of various formulas. However, sometimes this formula is not easy to write, and for each element of the calculation function is very easy to implement with Python, you can use the Frompyfunc function to calculate a single element of the function to convert to Ufunc function. This makes it easy to calculate the array of Ufunc functions that are generated. Let's take a look at an example.

We want to use a piecewise function to describe the triangular wave, which looks like this:

Triangle wave can be calculated with piecewise function

It is easy to write the following function to calculate the y-coordinate of a triangular wave point, as shown here:

def Triangle_wave (x, C, C0, HC):     # the period of the triangle wave is 1, so only the decimal part of the x-coordinate is taken for calculation    . if x >= c:r = 0.0    elif x < c0:r = X/C0 * HC    else: R = (c-x)/(c C0) * HC    return R

Obviously the Triangle_wave function can only calculate a single value and cannot be processed directly on the array. We can use the following method to first work with List comprehension, compute a list, and then use the array function to convert the lists to arrays:

x = Np.linspace (0, 2, + -in x])

This approach requires the use of a list containment syntax call function every time, which is cumbersome for multidimensional arrays. Let's take a look at how to use the Frompyfunc function to solve this problem:

Lambda x:triangle_wave (x, 0.6, 0.4, 1.0), 1, 1= Triangle_ufunc (x)

The invocation format for Frompyfunc is Frompyfunc (func, Nin, Nout), where Func is the function that computes a single element, Nin is the number of input parameters for this function, and Nout is the number of return values for this function. Although the Triangle_wave function has 4 parameters, since the last three C, C0, HC values are fixed throughout the calculation, the resulting Ufunc function actually has only one parameter. To satisfy this condition, we use a lambda function to wrap the parameters of the Triangle_wave. This way, the function passed into the FROMPYFUNC has only one parameter. In this way, efficiency is not too high, there is another way:

defTriangle_func (c, C0, HC):defTrifunc (x): x= X-int (x)#the period of the triangle wave is 1, so only the decimal part of the x-coordinate is taken for calculation .        ifX >= c:r = 0.0elifx < C0:R = X/c0 *HCElse: R = (c-x)/(C-C0) *HCreturnR#Use the Trifunc function to create a ufunc function that can be calculated directly from the array, but this function    #an object array is computed, and a type conversion is required    returnNp.frompyfunc (Trifunc, 1, 1) Y2= Triangle_func (0.6, 0.4, 1.0) (x)

We use the function Triangle_func to wrap three parameters of a triangular wave, within which a function trifunc,trifunc the trigonometric wave is defined and the function is calculated using Triangle_func parameters when called. Finally Triangle_func returns the result with the Frompyfunc conversion.

It is worth noting that the type of the array element computed by the function obtained by Frompyfunc is object, because the Frompyfunc function cannot guarantee that the data types returned by the Python function are exactly the same. It is therefore also necessary to Y2.astype (Np.float64) again to convert it to a double-precision floating-point array.

"Python" high-order features

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.