Special syntax for Python notes filter, map, reduce, lambda

Source: Internet
Author: User

filter (function, sequence): Executes function (item) on item in sequence, and the item that executes the result of true is composed of a list/string/ The Tuple (depending on the type of sequence) returns:

>>> def f (x): return x% 2! = 0 and x% 3! = 0 >>> filter (f, Range (2)) [5, 7, one,, 23]> ;>> def f (x): return x! = ' A ' >>> filter (F, "abcdef") ' Bcdef '

map (function, sequence): Executes function (item) on item in sequence, and the result of execution consists of a list return:

>>> def Cube (x): Return x*x*x >>> Map (cube, range (1, 11)) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]& gt;>> def Cube (x): return x + x ... >>> map (cube, "ABCDE") [' AA ', ' BB ', ' cc ', ' dd ', ' EE ']

In addition, the map supports multiple sequence, which requires that the function also supports the corresponding number of parameter inputs:

>>> def add (x, y): return x+y >>> Map (Add, Range (8), range (8)) [0, 2, 4, 6, 8, 10, 12, 14]

reduce (function, sequence, starting_value): The call function is iterated on the item order in sequence, and if there is starting_value, it can also be called as an initial value, for example, can be used to sum a list:

>>> def add (x, y): return x + y >>> reduce (add, range (1, 11)) 55 (note: 1+2+3+4+5+6+7+8+9+10) >>> Red UCE (Add, Range (1, 11), 20) 75 (note: 1+2+3+4+5+6+7+8+9+10+20)

Lambda: This is a fun syntax for Python, which allows you to quickly define the smallest function of a single line, similar to a macro in C, these functions, called Lambda, are borrowed from Lisp and can be used wherever functions are needed. using lambda in Python to create anonymous functions, the method created with Def is named. Lambda creates a function object, but does not assign the function object to an identifier, and Def assigns the function object to a variable. PYthon Lambda It's just an expression, and DEF is a statement.

>>> g = Lambda x:x * 2 >>> G (3) 6 >>> (Lambda x:x * 2) (3) 6

sorting with Lambda

Class User:def __init__ (Self, user_id): self.user_id = User_iddef __repr__ (self): return ' User ({}) '. Format (self.user_id if __name__ = = ' __main__ ': users = [user], User (3), User (]print usersprint sorted (users, Key=lambda u:u.user_id)
Where Key=lambda u:u.user_id can be replaced with key=attrgetter (' user_id '), the speed can be a bit faster.


we can also combine filter map reduce with lambda. function, you can simply write a line. For example

Kmpathes = Filter (lambda Kmpath:kmpath,                  map (Lambda Kmpath:string.strip (Kmpath), String.Split (L, ': ')))  

Looks like trouble, in fact, as in the language to describe the problem, very elegant.
Make a list of all the elements in L that are split with ': '. Each element of this list is made into a string strip, forming a list. Do a direct return operation on each element of this list (this place can be added to the filter limit) and eventually get a string that is ': ' In the split list, each string in the list is strip and can be filtered on a special string.

lambda expressionReturns an example of a function object: func = lambda X,y:x+yfunc equivalent to the following function def func (x, y): return x+y Note that DEF is a statement and lambda is an expression under which the lambda is the only way to use the def[( Lambda x:x*x) (x) for x in range (1,11)] The function in Map,reduce,filter can be generated with a lambda expression! map (function,sequence)Pass the worth parameter in the sequence to function, and return a list containing the result of the function execution. If function has two parameters, that is, map (FUNCTION,SEQUENCE1,SEQUENCE2). Example: Seek 1*1,2*2,3*3,4*4map (lambda x:x*x,range (1,5)) return value is [1,4,9,16] reduce (function,sequence)function receives only 2 parameters to function, the first value in sequence and the second worth parameter, then the return value of function and the third worth parameter to function, and then returns only one result. Example: 1 to 10 of the cumulative reduce (lambda x,y:x+y,range (1,11)) return value is 55. filter (function,sequence)The return value of a function can only be true or false to pass the value in the sequence to function individually, and if the return value of function (x) is true, the X is added to the return value of the filter. In general, the return value of filter is list, special cases such as sequence is a string or tuple, then the return value is the type of sequence. Example: Find the odd filter (Lambda X:x%2!=0,range (1,11)) return value between 1 and 10 [1,3,5,7,9] If sequence is a stringfilter (lambda X:len (x)!=0, ' Hello ') returns ' Hello ' filter (lambda x:len (x) ==0, ' hello ') return '

Special syntax for Python notes filter, map, reduce, lambda

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.