Analysis of map, reduce, and filter in Python

Source: Internet
Author: User
Tags iterable

1. First look at what is an iterable object

Take the built-in max function as an example to view its doc:
Copy codeThe Code is as follows:
>>> Print max. _ doc __
Max (iterable [, key = func])-> value
Max (a, B, c,... [, key = func])-> value

With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.
In the first form of the max function, the first parameter is an iterable object. In this case, what are iterable objects?
Copy codeThe Code is as follows:
>>> Max ('abcx ')
>>> 'X'
>>> Max ('20140901 ')
>>> '4'
>>> Max (1, 2, 3 ))
>>> 3
>>> Max ([1, 2, 4])
>>> 4
We can use yield to generate an iterable object (there are other methods ):
Copy codeThe Code is as follows:
Def my_range (start, end ):
''''''
While start <= end:
Yield start
Start + = 1
Run the following code:
Copy codeThe Code is as follows:
For num in my_range (1, 4 ):
Print num
Print max (my_range (1, 4 ))
Output:
Copy codeThe Code is as follows:
1
2
3
4
4


2. map

In http://docs.python.org/2/library/functions.html#map, map:
Copy codeThe Code is as follows:
Map (function, iterable ,...)
Apply function to every item of iterable and return a list of the results. if additional iterable arguments are passed, function must take that between arguments and is applied to the items from all iterables in parallel. if one iterable is shorter than another it is assumed to be extended with None items. if function is None, the identity function is assumed; if there are multiple arguments, map () returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation ). the iterable arguments may be a sequence or any iterable object; the result is always a list.
The map function uses a custom function to process every element in the iterable, and returns all the processing results in the form of 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 running result is:
Copy codeThe Code is as follows:
[1, 4, 16, 64]
[1, 4, 9, 16]
You can also use list derivation:
Copy codeThe Code is as follows:
Print [x * x for x in [1, 2, 4, 8]

3. reduce

In http://docs.python.org/2/library/functions.html#reduce, we will introduce reduce:
Copy codeThe Code is as follows:
Reduce (function, iterable [, initializer])
Apply function of two 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, is the accumulated value and the right argument, y, is the update value from the iterable. if the optional initializer is present, it is 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 is already very clear,
Copy codeThe Code is as follows: reduce (lambda x, y: x + y, [1, 2, 3, 4, 5])
Equivalent to computing
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 computing
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 following describes filter.pdf:
Copy codeThe Code is as follows:
Filter (function, iterable)
Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. if iterable is a string or a tuple, the result also has that type; otherwise it is always a list. if function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter (function, iterable) is equivalent to [item for item in iterable if function (item)] if function is not None and [item for item in iterable if item] if function is None.
The function parameter is used to process each element in the iterable. If the function returns true when processing an element, the element is returned as a list member. 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, 'awak ')
The running result is:
Copy codeThe Code is as follows:
Wke
This can also be achieved through list derivation:
Copy codeThe Code is as follows:
Print ''. join ([x for x in 'awak' if x! = 'A'])

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.