Python Lambda, filter, reduce and map

Source: Internet
Author: User

1. Lambda

The lambda operator or lambda function is a-to-create small anonymous functions, i.e. functions without a name.

It is convenient to create a function. Like what

  

def add (x, y): Return x+y

Using Lambda to write is

  

Lambda X,y:x+y

Very concise. This statement returns a function pointer, which you can assign, or coordinate with the map, reduce, and so on.

For example, if you want to multiply each value of list [1,2,3,4,5] by 2, return a list.

2. Map

Lambda with map is the most convenient.

R = Map (func, seq)

Map receives a func pointer and then functions to each member of the SEQ.

The example above is:

  

Map (Lambda x:x*2,[1,2,3,4,5])
[2, 4, 6, 8, 10]

    

3. Filtering

Similar to map, except that he filters the list and accepts a Func lambda expression, and then filters out if the expression is true.

Filter (function, list)

  

FIB = [0,1,1,2,3,5,8,13,21,34,55]filter (lambda x:x% 2, fib) [1, 1, 3, 5, 13, 21, 55]

Filters out even-numbered items directly.

4.Reducing

The function reduce (func, SEQ) continually applies the function func () to the sequence seq. It returns a single value.

If seq = [S1, S2, S3, ..., SN], calling reduce (func, seq) works like this:

[Func (S1, S2), S3, ..., SN]

[Func (Func (S1, S2), S3), ..., SN]

The func operation of the list is continued, resulting in a numeric value!

  

Reduce (lambda x,y:x+y, [47,11,42,13]) 113

This, for example, adds to the 47,11 in turn to [58,42,13]

And then add [100,13]

113

  

Python Lambda, filter, reduce and map

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.