Python Interview-reduce & Map & Filter

Source: Internet
Author: User

Python has a lot of interesting built-in functions, such as Reduce,map,filter,lambda,zip. has written about lambda and zip-related blogs. Continue writing about Reduce,map,filter.



Map

First use the Help method to look at the specific use of map.

Help (map) # resulthelp on built-in function map in module __builtin__:map (...)    Map (function, sequence[, sequence, ...]) List        Return A list of the results of applying the function to the items Of the    argument sequence (s).  If more than one sequence are given, the    function is called with an argument list consisting of the corresponding    I TEM of each sequence, substituting None for missing values when not all    sequences has the same length.  If the function is None, return a list of the items of the    sequence (or a list of tuples if more than one sequence).

Map functions, Map (function, sequences), and then return a list. If there is more than one sequence, then the corresponding element in each list is accessed according to function, and if the sequence is unequal, then none will be used instead of the insufficient element. If function is none, it returns a list, or if it is multiple lists, it returns a list with many tuples.


L1 = [1,2,3,4,5]def func (x):    return x*xprint map (func, L1) # result[1, 4, 9, 16, 25]

If it's a two sequences

L1 = [1,2,3,4,5]L2 = [6,7,8,9,10]def func (x, y):    return x+yprint map (func, L1, L2) # result[7, 9, 11, 13, 15]

The method has changed because it is two lists, so the method has two parameters.

For unequal lengths of sequences

L1 = [1,2,3,4,5,6]L2 = [6,7,8,9,10]def func (x, y):    return yprint map (func, L1, L2) # result[6, 7, 8, 9, ten, None]

We can see that the shorter list, the output of the time will be replaced by none.

Map can be used with lambda

L1 = [1,2,3,4,5]print map ((Lambda x:x **2), L1) # result[1, 4, 9, 16, 25]

When we use lambda as a function, we can pass in the list of function as sequence

def Square (x):        return (X**2) def Cube (x):        return (x**3) Funcs = [Square, cube]for R in range (5):    value = Map (Lam BDA X:x (R), Funcs)    print value    # result[0, 0][1, 1][4, 8][9, 27][16, 64]


If function is None,

L1 = [1,2,3,4,5]L2 = [6,7,8,9,10]print map (None, L1, L2) # result[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]


The map is like a for loop that operates on the elements in the sequence sequence.

From math import sqrtdef mymap (Afunc, aseq): result = []for x in ASeq:result.append (Afunc (x)) return Resultprint list (map (s) QRT, [1, 2, 3]) print mymap (sqrt, [1, 2, 3]) # result[1.0, 1.4142135623730951, 1.7320508075688772][1.0, 1.4142135623730951 , 1.7320508075688772]




Filter

Use Help to see the use of filter

Help (Filter) # Resulthelp on built-in function filter in Module __builtin__:filter (...)    Filter (function or None, sequence), list, tuple, or string        Return those items of sequence for which function (item ) is true.  If    function is None, and return the items is true.  If sequence is a tuple    or string, return the same type, else return a list.

The filter function, which is also filter (function,sequence), returns List,tuple, or string. Returns the element that is true after function has been judged. If function is none, then the element that returns true is returned. If sequence is a tuple or string, returns the same type, and returns a list if it is a different type.

Print List (range ( -5,5)) Print List (filter ((lambda x:x<0), Range ( -5,5)) # result[-5,-4,-3,-2,-1, 0, 1, 2, 3, 4][-5, -4,-3,-2,-1]

If function is None

Print List (filter (None, Range ( -5,5))) # result[-5,-4,-3,-2,-1, 1, 2, 3, 4]

Only 0 has no output, because 0 is considered false here.

Other types

def f (x):    return x! = ' A ' Print filter (f, ' abcdef ') # Resultbcdef



Reduce

Use Help to see the usage of reduce

Help (reduce) # resulthelp on built-in function, reduce in module __builtin__:reduce (...)    Reduce (function, sequence[, initial]), value        Apply a function of the of the arguments cumulatively to the items of a SEQ Uence, from left    to right, so as to reduce the sequence to a single value.    For example, reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5]) calculates (((((    1+2) +3) +4) +5).  If Initial is present, it's placed before the items    of the sequence in the calculation, and serves as a default when The    sequence is empty.


The reduce function, reduce (function,sequence[,initial]) returns a value. The elements in the sequence from left to right two two according to function operation, and finally left a value. For example, reduce (lambda x,y:x+y,[1,2,3,4,5]) The process of Running is ((((((((1+2) +3) +4) +5). Initial can be set as a default if sequence is empty.


def add (x, y): Return X+yprint (Add, Range (1,11)) print reduce (add, range (1,11), print reduce (add, [],20) # Resul T55 (1+2+3+4+5+6+7+8+9+10) (20+1+2+3+4+5+6+7+8+9+10) (default) <span style= "Font-family:arial, Helvetica, Sans-serif; " ></span>

The same can also be used with lambda

Print reduce ((lambda x, y:x * y), [1, 2, 3, 4]) # Result24 (1*2*3*4)


Python Interview-reduce & Map & Filter

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.