A brief analysis of map, reduce and filter in Python

Source: Internet
Author: User
1, first see what is Iterable object

Take the built-in Max function as an example to view its doc:
Copy the Code code as follows:


>>> Print max.__doc__
Max (iterable[, Key=func]), value
Max (A, B, C, ...) [, Key=func]) -Value

With a single iterable argument, return to its largest item.
With and or more arguments, return the largest argument.


In the first form of the Max function, its first argument is a Iterable object, so what are the Iterable objects?
Copy CodeThe code is as follows:


>>> Max (' Abcx ')
>>> ' x '
>>> Max (' 1234 ')
>>> ' 4 '
>>> Max ((+))
>>> 3
>>> Max ([1,2,4])
>>> 4


We can use yield to generate a Iterable object (and there are other ways):
Copy CodeThe code is as follows:


def my_range (start,end):
''' '''
While start <= end:
Yield start
Start + = 1


Execute the following code:
Copy CodeThe code is as follows:


For num in My_Range (1, 4):
Print num
Print Max (My_Range (1, 4))


Will output:
Copy CodeThe code is as follows:


1
2
3
4
4



2. Map

This introduces the map function in Http://docs.python.org/2/library/functions.html#map:
Copy the Code code as follows:


Map (function, iterable, ...)
Apply function to every item of iterable and return a list of the results. If additional iterable arguments is passed, function must take that many arguments and is applied to the items from all I Terables in parallel. If one iterable is shorter than another it's assumed to being extended with None items. If function is None and the identity function is assumed; If there is multiple arguments, map () returns a list consisting of tuples containing the corresponding items from all ITE Rables (a kind of transpose operation). The iterable arguments is a sequence or any iterable object; The result is always a list.


The map function uses a custom function to process each element in the iterable, returning all the processing results as a list. For example:
Copy CodeThe code is as follows:


def func (x):
''' '''
Return x*x

Print Map (func, [1,2,4,8])
Print Map (func, My_Range (1, 4))


The operating result is:
Copy CodeThe code is as follows:


[1, 4, 16, 64]
[1, 4, 9, 16]


You can also do this by listing deduction:
Copy CodeThe code is as follows:


print [x*x for x in [1,2,4,8]]

3. Reduce

The reduce function is described in Http://docs.python.org/2/library/functions.html#reduce as follows:
Copy the Code code as follows:


Reduce (function, iterable[, initializer])
Apply function of arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to A single value. For example, reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5]) calculates (((((1+2) +3) +4) +5). The left argument, X, are the accumulated value and the right argument, y, are the update value from the iterable. If the optional initializer is present, it's placed before the items of the iterable in the calculation, and serves as a Default when the iterable is empty. If initializer is not given and Iterable contains only one item, the first item is returned.


This has been introduced very clear,
Copy CodeThe code is as follows:

Reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5])


Equivalent to calculation
Copy CodeThe code is as follows:


(((((1+2) +3) +4) +5)


and
Copy CodeThe code is as follows:


Reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5],6)


Equivalent to calculation
Copy CodeThe code is as follows:


((((((((((6+1) +2) +3) +4) +5)


4. Filter

In Http://docs.python.org/2/library/functions.html#filter, the filter function is described as follows:
Copy the Code code as follows:


Filter (function, iterable)
Construct a list from those elements of iterable for which function returns TRUE. Iterable May is either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also have that type; Otherwise it is always a list. If function is a None, the identity function is assumed, which is, and all elements of iterable that is false is removed.

Note that the filter (function, iterable) is equivalent to [item for item ' in Iterable if function (item)] If function was not Non E and [item for item in Iterable if Item] if function is None.


The parameter function (the function) is used to process each element in the iterable, and if the function returns True when it processes an element, the element is returned as a member of the list. For example, filter out the character a in the string:
Copy CodeThe code is as follows:


def func (x):
''' '''
return x! = ' a '

Print filter (func, ' Awake ')


The operating result is:
Copy CodeThe code is as follows:


Wke


This can also be achieved by listing deduction:
Copy CodeThe code is as follows:


print '. Join ([x for X in ' Awake ' if x! = ' A '])
  • 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.