Wang yunqi's Python learning path (8)-functional programming, map (), reduce (), filter ()

Source: Internet
Author: User
Tags iterable string to number

Wang yunqi's Python learning path (8)-functional programming, map (), reduce (), filter ()

First of all, I wish you a happy New Year and a smooth job with few bugs !!!

I said that I continued to write articles during the Spring Festival holiday, but I was still lazy for a few days (I played SC2 for 4 days)

Today I wrote an article about Python. After all, I was too lazy to plug in various types of mobile phones to debug or something at my relatives' home. Besides, I did not get Python for a long time, so I wrote it. I don't have much nonsense and I started to get started !!

Functional Programming

What is a function?

Complex operations are divided into simple functions into simple operations, which are process-oriented, that isCThe general concept of such implementation.

What is a function?

The function has no variables. Any function, as long as the input is definite, the output is definite. The programming with the function as the most basic component is calledFunctional Programming(There are no variables in traditional functional programming, but in Python)

You do not need to define the variable type when declaring Python variables like this.

a=123

For java c

int a =123 ;

Variables in Python can also point to methods (functions can be understood as needed)

Here we use the max method as an example.

Print ('maximum function: ', max ([1, 2, 3,100, 20]); Result: Maximum function: 100

If the maximum value is 100, point the function to an object.

MaxValue = max; print ('object points to function maximum value: ', maxValue (10, 20) Result: object points to function maximum value: 20

So since a function can point to a variable, can the function be passed into another function as a parameter? (Guess) Let's try it!

This experiment uses the absolute value function abs.

C = absdef testABS (a, B, c): return c (a) + bprint ('test function result: ', testABS (-1,-9, c) Result: test function result:-8

That is, 1-9 =-8. In line with our ideas, we can pass in a function.

Map ()

The map method has two parameters. The first parameter is a function, and the second parameter is an Iterable (so you can input (), [] or anything)

Each result is generated separately, and the length of the returned Iterable object is not reduced.

Def testMAP (a): return a + aprint ('Return result: ', list (map (testMAP, (1, 2, 3, 4, 5) Result: returned results: [2, 4, 6, 8, 10]

Similar implementation, you can use a loop operation, such

IstValue = [] for x in [1, 2, 3, 4, 5,]: listValue. append (testMAP (x) print ('Return result: ', listValue)

The result is the same as the above map.

Add another example: int list to convert string list

Def toString (a): return str (a) print ('convert to string: ', list (map (toString, [1, 2, 3, 4]) Result: convert to a string: ['1', '2', '3', '4']

Each element in the original Iterable object does not have any relationship, and the reduce () function is the opposite.

Reduce ()

Reduce is also used to input two parameters. The first parameter is a function, and the second parameter is an Iterable. However, the difference between reduce and map is that it calculates the result and the next element of the sequence.

Def absAll (a, B): return abs (a) + abs (B) print ('returns the sum of the absolute values of all values', reduce (absAll, (-1, 2, -3,-10, 1) result: the process for returning the absolute values of all values and 17 is 1 + 2 = 33 + 3 = 66 + 10 = 1616 + 1 = 17

Then we can combine the previous toString operations (this time let him toInt) to calculate the sum of each, like this

# Map reduce combines def toInt (a): return int (a) print ('string to digit: ', toInt ("12") print (' combination results: ', reduce (absAll, list (map (toInt, ["1", "2", "3"]) Result: string to number: 12 combination results: 6

In this way, your programs can become richer and easier to use.

Filter ()

The filter () function also requires two parameters. The first parameter is a function, and the second parameter is a sequence. The filter traverses each element, and then judges whether the current element is True or False based on the logic of the first parameter function. True is added to the new sequence, and False is removed.

Let's take a look at the example:

Def checkValue (a): return a-5> 0 print ('judge whether> 5', list (filter (checkValue, [1, 6, 9, 3]) result: Check whether the value is greater than 5 [6, 9].

Returns a new sequence with a value that conforms to the logic of the first function.

Related Article

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.