Map, filter, reduce, Lambda in Python

Source: Internet
Author: User

Python special Syntax: filter, MAP, reduce, Lambda (from "Play with Python ")

Python has built-in interesting but useful functions that fully reflect the charm of Python!

Filter (function, sequence ):Execute function (item) in sequence for items in sequence, and combine items with the execution result of true into a list/string/tuple (depending on the sequence type) to return:

>>> 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'

Map (function, sequence ):Execute function (item) in sequence for items in sequence. See the execution result to form a list and return:

>>> Def cube (x): Return x * x
>>> Map (cube, range (1, 11 ))
[1, 8, 27, 64,125,216,343,512,729,100 0]

>>> Def cube (x): Return x + x
...
>>> Map (cube, "ABCDE ")
['A', 'bb ', 'cc', 'dd', 'ee']

In addition, 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]

Reduce (function, sequence, starting_value ):Call the function sequentially for items in sequence. If starting_value exists, it can also be called as an initial value. For example, it can be used to sum the list:

>>> Def add (x, y): Return x + y
>>> Reduce (ADD, range (1, 11 ))
55 (Note: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10)

>>> Reduce (ADD, range (1, 11), 20)
75 (Note: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 20)

lambda: This is an interesting syntax supported by python, it allows you to quickly define the smallest function of a single row, similar to Macros in C language. These Lambda functions are borrowed from lisp and can be used in any function that requires them:
>> G = Lambda X: x * 2
>> G (3)
6
>>> (lambda X: x * 2) (3)
6

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.