Introduction to filter map reduce of Python built in functions

  • 2020-04-02 14:27:12
  • OfStack

Python has some very interesting and useful functions built into it, such as filter, map and reduce, which all process a set.


1. The filter function Function as a filter. A Boolean function Boolean _func is called to iterate over the elements in each seq. Returns a sequence of elements that causes Boolean _seq to return true.


>>> N=range(10)
>>> print filter(lambda x:x>5,N)
[6, 7, 8, 9]

2. The map function Func ACTS on each element of a given sequence and provides the return value with a list.


>>> N1=[1,2,3]
>>> N2=[6,5,4]
>>> map(lambda x,y:x+y,N1,N2)
[7, 7, 7]
>>> map(lambda x:x+3,N1)
[4, 5, 6]

3. Reduce function , func is a binary function, acting func on the elements of seq sequence, carrying a pair at a time (the previous result and the elements of the next sequence), continuously acting the existing result and the next value on the obtained subsequent result, and finally reducing our sequence to a single return value.


>>> N=range(1,101)
>>> reduce(lambda x,y:x+y,N)
5050

Example 1: using map and reduce to add the factorial of 5 (5! + 4! + 3! + 2! + 1!


>>>print reduce(lambda x,y:x*y,range(1,6))
>>>print reduce(lambda x,y:x*y,range(1,5))
>>>print reduce(lambda x,y:x*y,range(1,4))
>>>print reduce(lambda x,y:x*y,range(1,3))
>>>print reduce(lambda x,y:x*y,range(1,2))
'''

The results for


120
24
6
2
1
'''

Turn the result of the previous step into a factorial list


>>>print map(lambda a:reduce(lambda x,y:x*y,range(1,a+1)),range(1,6))
[1, 2, 6, 24, 120]

Finally, add up the factorial list. Problem number one


>>>print reduce(lambda m,n:m+n,map(lambda a:reduce(lambda x,y:x*y,range(1,a+1)),range(1,6)))
153

Example 2: use filter to filter out primes within 100~200
Prime Numbers are also called prime Numbers. A number greater than 1 that is not divisible by any other natural number except 1 and the integer itself


>>>filter(lambda N:len(filter(lambda M:N%M==0,range(2,int(N**0.5)+1)))==0,range(100,201))

Related articles: