PYTHON:LAMBDA, filter, map, reduce

Source: Internet
Author: User

Lambda is the keyword. Filter,map,reduce is a built-in function.

Lambda:Implements a single-line minimum function in Python.
g = Lambda x:x * 2 #相当于def g (x):    return x*2
Map function

The map () function receives two parameters, one is a function, the other is a sequence, and map passes the incoming function to each element of the sequence sequentially, returning the result as a new list.
To illustrate:
For example, we have a function f (x) =x2, to function in a list [1, 2, 3, 4, 5, 6, 7, 8, 9], you can use map () to achieve the following:

Now, we use Python code to implement:

>>> def f (x): ...     return x * x...>>> map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) [1, 4, 9, 16, 25, 36, 49, 64, 81]
Reduce function

Reduce functions a function in a sequence [X1, x2, x3 ...] , the function must receive two parameters, and reduce calculates the result and the next element of the sequence, and the effect is:

Reduce (f, [X1, x2, X3, x4]) = f (f (f (x1, x2), x3), x4)

For example, to sum a sequence, it can be implemented with reduce:

>>> def add (x, y): ...     return x + y...>>> reduce (add, [1, 3, 5, 7, 9]) 25
Filter function

Python's built-in filter () function is used for filtering sequences. Like map (), filter () also receives a function and a sequence. When different from map (), filter () applies the incoming function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is true or false.

True reserved, false discarded
For example, in a list, delete even numbers, keep only odd numbers, and you can write:

def is_odd (n):    return n% 2 = = 1filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15]) # results: [1, 5, 9, 15]

The key is to implement a "filter" function correctly by using the filter () as a high-order function.

PYTHON:LAMBDA, filter, map, reduce

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.