Transferred from: http://www.jianshu.com/p/7fe3408e6048
1. Map (FUNC,SEQ1[,SEQ2 ...]) The map () function in Python's functional programming is to act on each element of the SEQ with Func and give the return value with a list. If Func is none, the action is through ZIP ().
When SEQ has only one, the Func function is applied to each element of this seq and a new seq is obtained.
For example, (assuming we want to get the remainder of the number%3 in a list, we can write the following code):
Print map (Lambda x:x%3, range (6))>>> [0,1,2,0,1,2]print for in range (6)]>>> [0,1,2,0,1,2]
When the SEQ is more than one, the map can perform the process as shown in parallel to each SEQ:
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.
>>>PrintMapLambdax,y:x*y,[1,2,3],[4,5,6])>>> [4,10,18]#The following code does not only implement multiplication, it also implements addition, and puts the product and sum in a single tuple. >>>PrintMapLambdaX, Y: (X*y,x+y), [1,2,3],[4,5,6])>>> [(4,5), (10,7), (18,9)]#when Func is none, the goal is to merge elements of multiple lists at the same location into a tuple, which now has a dedicated function zip ()>>>PrintMap (none,[1,2,3],[4,5,6])>>> [(1,4), (2,5), (3,6)]>>>PrintZip ([1,2,3],[4,5,6])#It is important to note that SEQ of different lengths cannot execute the map function, and there will be type errors
2, Reduce (func, seq[, Init]) Python
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 a nutshell, a visual example:
>>> reduce (func,[1,2,3]) = Func (func), 3)
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:
print reduce (lambda x,y:x*y,range (1,n+1))>>># If you want to get twice times the factorial value, Then you can use INIT, the optional parameter , m=2n=5print reduce (lambda x,y:x*y,range (1,n+1), M)
Go Python functional Programming--map (), Reduce ()