Python filter | Map | reduce | Use of Lambda __python

Source: Internet
Author: User

1.filter (function, sequence): performs a function (item) on the item in sequence, and makes an item that executes the result to true list/string/ 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, 11, 13, 17, 19 ,
>>> def f (x): return x!= ' a ' 
>>> filter (F, "abcdef") 
' Bcdef '

2.map (function, sequence):Perform a function (item) in sequence on the item in sequence, see the Execution results form a list return:

>>> def Cube (x): return x*x*x 
>>> map (cube, range (1, one)) 
[1, 8, 27, 64, 125, 216, 343, 512, 729 , 1000]
>>> def Cube (x): return x + x 
... 
>>> map (Cube, "ABCDE") 
[' AA ', ' BB ', ' cc ', ' dd ', ' ee ']
Another map also supports multiple sequence, This 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)) C16/>[0, 2, 4, 6, 8, 10, 12, 14]


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

>>> def Add (x,y): return x + y 
>>> reduce (add, range (1, one)) 
55 (note: 1+2+3+4+5+6+7+8+9+10)
& gt;>> reduce (Add, range (1, a) 
75 (note: 1+2+3+4+5+6+7+8+9+10+20)

4.lambda:This is a very interesting syntax that Python supports, 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 a function is needed:
>>> g = Lambda x:x * 2 
>>> g (3) 
6 
>>> (Lambda x:x * 2) (3) 
6

-----------

Reference: http://www.cnblogs.com/longdouhzt/archive/2012/05/19/2508844.html



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.