Use of the zip, map, reduce, and lambda functions in Python

Source: Internet
Author: User
Tags python list

Plane ticket

Lambda is just an expression, and the function body is much simpler than def.

The body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda expression.

A lambda expression acts as a function sketch. Allows the definition of a function to be embedded within the code.

Here's an example:

Defines a lambda expression that evaluates to three numbers.

Let's look at an example:

Use a lambda expression to find the factorial of N.

------------------------------

Lambda expressions can also be used in Def functions.

See Example:

This defines an action function that returns a lambda expression. Where the lambda expression obtains the value of the variable name x for the upper def Scope.

A is the return value of the action function, a (22), which is the lambda expression called the action return.

It is also possible to write def directly into lambda form. As follows

Zip () function usage

Zip () is an intrinsic function of Python that takes a series of iterated objects as parameters, packages the corresponding elements in the object into tuple (tuples), and then returns a list of these tuples. If the length of the passed parameter is not equal, the length of the returned list is the same as the object with the shortest length in the parameter. Using the * operator, you can unzip the list (decompression), see the following example to understand:

1 2 3 4 5 6 7 8 9

>>> a = [+ +]
>>> B = [4,5,6]
>>> C = [4,5,6,7,8]
>>> zipped = Zip (A, B)

[(1, 4), (2, 5), (3, 6)]
>>> Zip (a,c)
[(1, 4), (2, 5), (3, 6)]
>>> Zip (*zipped)
[(1, 2, 3), (4, 5, 6)]

For this is not a very common function, here are a few examples to illustrate its use:

* Two-dimensional matrix transformation (matrix of the row and column interchange)

For example, we have a two-dimensional matrix that is described by a list
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]
With the Python list derivation method, we can also easily complete this task.

1 2

Print [[Row[col] for Row under a] for Col in range (len (a[0))]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Another confusing approach is to use the ZIP function:

1 2 3) 4 5

>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]
>>> Zip (*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> Map (List,zip (*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

This method is faster but more difficult to understand, the list as a tuple decompression, just get our "Row and column swap" effect, and then by applying the list () function to each element, convert the tuple to list

Python functional Programming--map (), Reduce ()

1.map ()

Format:map( func, seq1[, seq2...] )

Functions in Python's functional programming map() are to act on each element of the SEQ with Func and give the return value with a list. If Func is None, the function is the same zip() .

when the SEQ has only one , the Func function is applied to each element of this seq and a new seq is obtained. Shows how the map () function works when there is only one seq (the source of this picture: "Core Python Programming (2nd Edition)").

As you can see, each element in the SEQ is acting as a func function, resulting in a list of Func (Seq[n]).

Here is an example to illustrate. Suppose we want to get the remainder of the number%3 in a list, then we can write the following code.

Python-Functional programming map using (a seq)Python
123456 # using Mapprint map( Lambda x: x%3, range(6 ) # [0, 1, 2, 0, 1, 2] #使用列表解析print [x%3 for x in range(6)] # [0, 1, 2, 0, 1, 2]

This is the same as the last time filter() , using the method of list parsing instead of map execution. So, when is list parsing not a substitute for map?

Originally, when the SEQ is more than one , map can execute the process as shown in parallel to each SEQ:

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.

Python-Functional programming map using (multiple seq)Python
1 PrintMap(LambdaX,Y:X * y, [1  2, < Span class= "CRAYON-CN" >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.

Python-Functional programming map using (multiple seq)Python
1 PrintMap(LambdaX,Y:(X*Y,X+ y) , [1  2, < Span class= "CRAYON-CN" >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() .

Python-Functional Programming map use (Func is None)Python
123 PrintMap ( none,< Span class= "crayon-h" > [1, 2, 3], [4,  5, 6] )   < Span class= "Crayon-c" ># [(1, 4), (2, 5), (3, 6)]   print zip (  [1, 2, 3], [4,  5, 6] )   < Span class= "Crayon-c" ># [(1, 4), (2, 5), (3, 6)]

It is important to note that multiple seq of different lengths cannot execute the map function and there will be a type error.

2.reduce ()

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, [1, 2,3] ) = func( func(1, 2), 3)

The following is a diagram of the work process of the reduce function:

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.

reduce usage of python functional programmingPython
12 n = 5 PrintReduce(lambda x,< Span class= "crayon-h" > 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.

reduce usage of python functional programmingPython
123 m = 2 n = 5 PrintReduce(LambdaX,Y: x < Span class= "Crayon-o" >* y, range ( 1, n  + 1< Span class= "crayon-h" > ) , < Span class= "crayon-i" >m )    #

Use of the zip, map, reduce, and lambda functions in Python

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.