Special syntax in Python: Introduction to filter, map, reduce, and lambda

Source: Internet
Author: User
This article mainly introduces the special syntax in Python: filter, map, reduce, and lambda. This article provides code examples for this special syntax. For more information, see 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:

The code is as follows:


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

The code is as follows:


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

The code is as follows:


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

The code is as follows:


>>> 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, these lambda functions are borrowed from LISP, it can be used in any function:

The code is as follows:


>>> G = lambda x: x * 2
>>> G (3)
6
>>> (Lambda x: x * 2) (3)
6

We can also combine filter map reduce and lambda to write a simple row of functions.
For example:

The code is as follows:


Kmpathes = filter (lambda kmpath: kmpath,
Map (lambda kmpath: string. strip (kmpath ),
String. split (l ,':')))


It looks troublesome. In fact, it is as elegant as it is to describe the problem in a language.
Splits all elements in l by ':' to produce a list. Strip each element of the list to form a list. Perform a direct return operation on each element in the list (filter conditions can be added here) to obtain a list separated, each string in the list is strip and can filter special strings.

---------------------------------------------------------------

A lambda expression returns a function object.
Example:

The code is as follows:


Func = lambda x, y: x + y
Func is equivalent to the following function.
Def func (x, y ):
Return x + y


Note that def is a statement and lambda is an expression.
In this case, you can only use lambda instead of def.

The code is as follows:


[(Lambda x: x * x) (x) for x in range ()]

Functions in map, reduce, and filter can all be generated using lambda expressions!

Map (function, sequence)
Pass the values in the sequence parameter to the function one by one and return a list containing the function execution result.
If a function has two parameters: map (function, sequence1, sequence2 ).

Example:
1*4

The code is as follows:


Map (lambda x: x * x, range (1, 5 ))


The return value is [,].

Reduce (function, sequence)

Function can receive only 2 parameters.
First, pass the first and second values in the sequence parameter to the function, and then pass the function return value and the third value to the function parameter.
Function, and then only one result is returned.

Example:
Calculate the sum of 1 to 10

The code is as follows:


Reduce (lambda x, y: x + y, range (1, 11 ))


The return value is 55.

Filter (function, sequence)

The return value of a function can only be True or False.
Pass the values in sequence one by one to the function. if the return value of function (x) is True, add x to the return value of filter. In general, the return value of filter is list. in special cases, if sequence is string or tuple, the return value is of the sequence type.

Example:
Find the odd number between 1 and 10.

The code is as follows:


Filter (lambda x: x % 2! = 0, range (1, 11 ))


Return value

The code is as follows:


[1, 3, 5, 7, 9]



If sequence is a string

The code is as follows:


Filter (lambda x: len (x )! = 0, 'Hello') returns 'Hello'
Filter (lambda x: len (x) = 0, 'Hello') returns''

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.