Python function Learning: lambda (), filter (), map (), reduce ()

Source: Internet
Author: User
Tags filter in python

1. Lambda ()

A lambda () is an anonymous function in Python with the following syntax:

Lambda [arg1[, arg2, ... argn]]: expression

Here's an example of a 1+2=3.

>>> fun = Lambda x,y:x+y

>>> Fun (1,2)

3

>>> (lambda x,y:x+y) (1,2)

3

2, filter ()

Filter (function, sequence): Performs a function (item) on the item in sequence, and makes an item that executes the result to true list/string/ Tuple (depending on the type of sequence) returns:

>>> def f (x): return x 2!= 0 and x 3!= 0

>>> filter (F, Range (2, 25))

[5, 7, 11, 13, 17, 19, 23]

>>> def f (x): return x!= ' a '

>>> filter (F, "abcdef")

' Bcdef '

3, Map ()

Map (function, sequence): Performs a function (item) in sequence on the item in sequence, see the Execution results form a list return:

>>> def Cube (x): Return x*x*x

>>> Map (cube, range (1, 11))

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

>>> def Cube (x): return x + x

...

>>> map (Cube, "ABCDE")

[' AA ', ' BB ', ' cc ', ' dd ', ' EE ']

The map also supports multiple sequence, which requires that the function also supports the corresponding number of parameter inputs:

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

>>> Map (Add, Range (8), range (8))

[0, 2, 4, 6, 8, 10, 12, 14]

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.