Python "Map, reduce, filter" built-in function usage instructions

Source: Internet
Author: User

A: Map

Map (...)    Map (function, sequence[, sequence, ...]) list

Description

Execute function (item) on item in sequence, and the result output is list.

Example:

 >>> Map (str, range (5)) #对range (5) for STR operations [' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 '] #返回列表 >>> def A DD (n): Return n+n ... >>> map (add, Range (5)) #对range (5) for the add operation [0, 2, 4, 6, 8]>>> map (lambda x: X+x,range (5)) #lambda function, each + itself [0, 2, 4, 6, 8] 
>>> map (lambda x:x+1,range) #lambda function, each +1
[1, 2, 3, 4, 5, 6, 7, 8, 9, []
>>> map (Add, ' zhoujy ') [' zz ', ' hh ', ' oo ', ' uu ', ' JJ ', ' yy '] #想要输入 multiple sequences , need to support multiple parameters of the function, note that the length of each sequence must be the same, otherwise error:>>> def add (x, y): return x+y ... >>> map (add, ' zhoujy ', ' Python ') [' ZP ', ' hy ', ' ot ', ' uh ', ' Jo ', ' yn ']>>> def add (x, Y, z): Return x+y+z ... >>> map (add, ' zhoujy ', ' Python ', ' Test ') # ' test ' is longer than the other 2 small traceback (most recent call last): File "<stdin>", line 1, in <module>typ Eerror:add () takes exactly 2 arguments (3 given) >>> map (Add, ' zhoujy ', ' Python ', ' testop ') [' zPt ', ' Hye ', ' ots ', ' u HT ', ' Joo ', ' YNP ']

Two: Reduce

Reduce (...)    Reduce (function, sequence[, initial]), value

Description

For the item order in sequence, the function must be called with 2 parameters. If there is a 3rd argument, the initial value can continue to be called, returning a value.

Example:

>>> def add (x, y): return x+y ... >>> reduce (add,range)        #1 +2+3+...+945>>> Reduce (add , Range (one))        #1 +2+3+...+1055>>> reduce (lambda x,y:x*y,range (1,3), 5)           #lambda function, 5 is the initial value, 1*2*510> >> Reduce (lambda x,y:x*y,range (1,6))             #阶乘,1*2*3*4*5120>>> reduce (lambda x,y:x*y,range (1,6), 3)           #初始值3, and the results *3360 again.
>>> reduce (lambda x,y:x+y,[1,2,3,4,5,6]) #1 +2+3+4+5+6

Three: Filter

Filter (...)    Filter (function or None, sequence), list, tuple, or string

Description

Execute function (item) on item in sequence and execute the result to True (! =0) item consists of a list/string/tuple (depending on the type of sequence) returned, false exits (0) for filtering.

Example:

>>> def div (n): Return n%2 ... >>> Filter (Div,range (5))                    #返回div输出的不等于0的真值 [1, 3]>>> Filter (Div,range) [1, 3, 5, 7, 9]>> > Filter (lambda x:x%2,range)        #lambda function returns an odd number, returning the list [1, 3, 5, 7, 9]>>> filter (lambda x:not x%2,range (1 0)) [0, 2, 4, 6, 8]>>> def fin (n): return n!= ' z '                #过滤 ' z ' function, Z returns false ... >>> filter (FIN, ' zhoujy ') c4/># ' z ' is filtered ' houjy ' >>> filter (lambda x:x! = ' Z ', ' zhoujy ')     #labmda返回True值 ' houjy ' >>> filter ( Lambda x:not x== ' z ', ' zhoujy ')  #返回: String ' houjy '

A lambda expression is used in all of the examples above, for example, more information here.

>>> A=lambda x:x+3>>> A (2) 5>>> A=lambda x,y:x+y>>> A (2,3) 5

Iv. Application of Map,reduce,filter

1): Achieve 5!+4!+3!+2!+1!

#!/usr/bin/env python#-*-coding:utf-8-*-def add_factorial (n):    empty_list=[]           #声明一个空列表, save the results of each factorial to facilitate the addition of these results For    i in map (lambda X:x+1,range (n)):    #用传进来的变量 (n) to generate a list with the map +1,eg:range (5) = [1,2,3,4,5]        a= Reduce (lambda x,y:x*y,map (i))   #生成阶乘, remove 0        empty_list.append (a) from the list by using map            Append the factorial result to the empty list    return empty_listif __name__ = = ' __main__ ':    import sys#2 Select # (a)    try:        n = input (" Enter a number (int): ")        result=add_factorial (n)   #传入变量        print reduce (lambda x,y:x+y,result)      # Factorial result addition    except (nameerror,typeerror):        print "That's not a number!" # (ii) #    result = add_factorial (int (sys.argv[1]))   #传入变量 #    print reduce (lambda x,y:x+y,result)      # Factorial result addition

Results:

2): Select the prime number within 100~200

Ideas:

Prime numbers are: only 1 and its own two factors, such as 2, 3, 5, 7 are prime numbers, which can be divisible by 1 and itself, 1 is not prime.
For example, a number N, to see if it is prime, it is necessary to see: There is no divisible "2,n" between the number of X (does not contain itself), that is, whether the n%x is 0, if not for prime numbers.
So the algorithm we're going to implement is: Take a number N, remove the number x between "2,n" to get prime numbers, namely: N/2,n/3,......,n/n-2,n/n-1 ===> N/range (2,n)

#!/usr/bin/env python#-*-coding:utf-8-*-def is_prime (start,stop):    Stop  = stop+1     #包含列表右边的值    prime =  Filter (lambda X:not [x%i for I in range (2,x) if x%i = = 0],range (start,stop))   #取出质数, x number of print from range (start,stop)    Primeif __name__ = = ' __main__ ':    try:        start = input ("Enter A start Number:")    except:        start = 2   #开 Start value default 2    try:        Stop  = input ("Enter a Stop number  :")    except:        stop  = 0   #停止数, default 0, That is, no value is returned    is_prime (start,stop)

Results:

[Email protected]:~/desktop/python/4$ Python prime.py Enter A start number:enter a stop  number:10[2, 3, 5, 7][email Prote cted]:~/Desktop/python/4$ Python prime.py Enter A start number:10enter a stop  number:20[11, +, 19][email protected]: ~/Desktop/python/4$ Python prime.py Enter A start number:enter a stop number  : []

Python "Map, reduce, filter" built-in function usage instructions

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.