Translation PYTHON Functions-map, FILTER, and REDUCE

Source: Internet
Author: User

Map, filter, and reduce

Python provides several functions that enable functional programming. These functions have handy features that can be easily written in Python.
Functional programming is all about expressions. We can say that functional programming is an expression-oriented programming.

The expression-oriented functions provided by Python are:
Map (afunction, asequence)
Filter (afunction, asequence)
Reduce (afunction, asequence)
Lambda
List comprehension

Map
One of the common things we do with lists and other sequence is to apply actions to each item and collect the results.
For example, you can easily update all items in the list by using the For Loop update operation:

>>> items = [1, 2, 3, 4, 5]>>> squared = []>>> for x in items:    squared.append(x ** 2)>>> squared[1, 4, 9, 16, 25]

Since this is a common operation, we actually have a built-in feature that can do most of the work for us.
The map (afunction,asequence) function applies the passed-in function to each item in an object that iterates, and returns a list containing the results of all function calls.

>>> items = [1,2,3,4,5]>>> def sqr(x):return x ** 2>>> list(map(sqr,items))[1,4,9,16,25]

We apply a user-defined function to each item of the list. Map calls the SQR on item in each list and collects all the return values into a new list. Because the map needs to pass in a function, it happens to be one of the usual places for lambda:

>>> list(map((lambda x: x **2), items))[1, 4, 9, 16, 25]

In the short example above, the lambda function does a square operation on each item in the list. As mentioned earlier, the map is defined as:
Map (afunction, asequence)

Although we still use LAMDA as a function, we can take a list of functions as a sequence:

def square(x):        return (x**2)def cube(x):        return (x**3)funcs = [square, cube]for r in range(5):    value = map(lambda x: x(r), funcs)    print value

Output Result:

[0,0][1,1][4,8][9,27][16,64]

Because using map is equivalent to looping, we can always write a common mapping tool:

>>> def mymap(aFunc, aSeq):    result = []    for x in aSeq: result.append(aFunc(x))    

Because map is built-in, it is always available and works the same way all the times. It also has some performance benefits because it is usually faster than manually coded loops. In addition, map can be used in a more advanced way. For example, given multiple sequence parameters, it sends the items taken in parallel as different parameters to the function:

As shown in the example above, for multiple sequences, map () requires n-parameter functions for the nth sequence. In this example, the POW function has two parameters in each call.

Here is another example of a map () that adds two elements to a list:

x = [1,2,3]y = [4,5,6]from operator import addprint map(add, x, y)  # output [5, 7, 9]

The map call resembles a list-understanding expression. But map applies a function call to each item, not an arbitrary expression. Because of this limitation, it is a less generic tool. However, in some cases, mappings may be faster than list parsing, such as mapping built-in functions. And the map requires less coding.
If the function is none, the identity function is assumed, or if there are multiple parameters, map () returns a list of tuples that contain the corresponding items in all iterations (one transpose operation). An iterative parameter may be a sequence or any object that can be iterated; The result is always a list.

>>> m = [1,2,3]>>> n = [1,4,9]>>> new_tuple = map(None, m, n)>>> new_tuple[(1, 1), (2, 4), (3, 9)]

For Python3, we might want to use Itertools.zip_longest instead:

>>> m = [1,2,3]>>> n = [1,4,9]>>> from itertools import zip_longest>>> for i,j in zip_longest(m,n):...    print(i,j)... 1 12 43 9

Zip_longest () causes Iterators to aggregate elements from two iterators (M&N).

Filter, reduce
As the name implies, the filter extraction function returns true for each element in the sequence. The intention to reduce the function is slightly less obvious. This feature reduces the list to a single value by providing a feature combination element. The map function is the simplest function in the Python built-in function for functional programming.
These tools apply functions to sequences and other iterations. Filter filters out the iterm based on the test function as a filter and applies the functionality to the item pair and reduces the running results. Because they return iterators, both scopes and filters require a list call to display all the results in Python 3.0.

For example, the following filter call picks out items that are less than 0 in the sequence:

When the function returns true for a sequence or an iteration of an item, the result is added to the results list. Like map, this function is roughly equivalent to a for loop, but it is built-in and fast:

>>> result = []>>> for x in range(-5, 5):    if x < 0:        result.append(x)        >>> result[-5, -4, -3, -2, -1]

Here is another use case for filter (): Find the intersection of two lists:

a = [1,2,3,5,7,9]b = [2,3,5,6,7,8]print filter(lambda x: x in a, b)  # prints out [2, 3, 5, 7]

Please note that we can do the same thing on the list understanding:

a = [1,2,3,5,7,9]b = [2,3,5,6,7,8]print [x for x in a if x in b] # prints out [2, 3, 5, 7]

Reduce is a functools in Python 3.0. This is more complicated. It accepts an iterator to handle it, but it is not an iterator by itself. It returns a single result:

>>> from functools import reduce>>> reduce( (lambda x, y: x * y), [1, 2, 3, 4] )24>>> reduce( (lambda x, y: x / y), [1, 2, 3, 4] )0.041666666666666664

In each step, reduce the delivery of the current product or department and the next item in the list to the incoming lambda function. By default, the first item in a sequence initializes the starting value.
Here is the For loop version of the first call, hard-coded inside the loop:

>>> L = [1, 2, 3, 4]>>> result = L[0]>>> for x in L[1:]:    result = result * x>>> result24

Let's make our own version of reduce.

>>> def myreduce(fnc, seq):    tally = seq[0]    for next in seq[1:]:        tally = fnc(tally, next)    

We can connect a string of strings to make a sentence. Use Dijkstra for a quote about the wrong name:

import functools>>> L = ['Testing ', 'shows ', 'the ', 'presence', ', ','not ', 'the ', 'absence ', 'of ', 'bugs']>>> functools.reduce( (lambda x,y:x+y), L)'Testing shows the presence, not the absence of bugs'>>> We can get the same result by using join :>>> ''.join(L)'Testing shows the presence, not the absence of bugs'

We can also use operators to produce the same results:

>>> import functools, operator>>> functools.reduce(operator.add, L)'Testing shows the presence, not the absence of bugs'

The built-in reduce also allows an optional third parameter to be placed before the item in the sequence as the default result when the sequence is empty.

Translation PYTHON Functions-map, FILTER, and REDUCE

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.