Several important python functions (lambda, filter, reduce, map, zip) and pythonlambda

Source: Internet
Author: User

Several important python functions (lambda, filter, reduce, map, zip) and pythonlambda

1. Anonymous function lambda

Lambda argument1, argument2,... argumentN: expression using arguments

 

1. lambda is an expression rather than a statement.

Because of this, lambda can appear where def is not allowed in python syntax-for example, in a list constant or in a function call parameter, as an expression, lambda returns a value (a new function) that can be selectively assigned to a variable name. On the contrary, the def statement always has to assign a new function to a variable name in the header, instead of returning the function as a result.

2. The body of lambda is a single expression, not a code block.

Lambda is designed for writing simple functions, and def is used to process larger tasks.

Example:

>>> F = lambda x, y, z: x + y + z

>>> F (2, 3, 4)

9

>>> X = (lambda a = "inherit", B = "fie", c = "foe": a + B + c)

>>> X ("wee ")

'Weefoe'

 

Lambda is usually used to write jump tables, as shown below:

>>> L = [lambda x: x ** 2,

Lambda x: x ** 3,

Lambda x: x ** 4]

>>> For f in L:

Print (f (2 ))

4

8

16

>>> Print (L [0] (3 ))

9

 

Nested lambda:

>>> Def action (x ):

Return (lambda y: x + y)

>>> Act = action (99)

>>> Act (2)

101

>>> Action = (lambda x: (lambda y: x + y ))

>>> Act = action (99)

>>> Act (2)

101

>>> (Lambda x: (lambda y: x + y) (99) (2)

101

 

Ii. map Functions

Map (function, sequence [, sequence,...])-> iterator

 

We can see from the definition that the first parameter of this function is a function, the remaining parameter is one or more sequences, and the return value is an iterator.

Function can be understood as a one-to-one or multiple-to-one function. map calls the function by each element in the parameter sequence and returns the iterator containing the return value of each function.

Returns an iteratable object. You need to call a list to display all the results.

>>> List (map (lambda x: x + 2, [1, 2, 3])

[3, 4, 5]

>>> List (map (pow, [1, 2, 3], [2, 3])

[1, 8, 81]

 

Iii. filter functions

The filter function filters the specified sequence.

 

Filter Function Definition:

Filter (function or None, sequence)-> iterator

The filter function calls the function for each element in the sequence parameter. The final returned result contains the element whose call result is True.

Returns an iteratable object. You need to call a list to display all the results.

>>> List (filter (lambda x: x> 0), range (-5 )))

[1, 2, 3, 4]

>>> List (filter (None, range (-5 )))

[-5,-4,-3,-2,-1, 1, 2, 3, 4]

If the function is None, an iterator containing non-null elements is returned.

 

Iv. reduce Functions

Reduce function. reduce function accumulates the elements in the parameter sequence.

 

Reduce Function Definition:

Functools. reduce (function, iterable [, initializer]) # reduce in python3 is in functools Module

The function parameter is a function with two parameters. reduce extracts an element from the iterable in turn, and calls the function again with the result of the last function call.

When you call a function for the first time, if the initial parameter is provided, the first element and initial in iterable are used as the parameters to call the function. Otherwise, the first two elements in iterable are used as parameters to call the function.

It is equivalent:

Def reduce (function, iterable, initializer = None ):

It = iter (iterable)

If initializer is None:

Value = next (it)

Else:

Value = initializer

For element in it:

Value = function (value, element)

Return value

 

>>> Functools. reduce (lambda x, y: x + y, [1, 2, 4])

10

>>> Functools. reduce (lambda x, y: x + y, [1, 2, 4], 10)

20

>>> Functools. reduce (lambda x, y: x * y, [1, 2, 4])

24

 

If the initial parameter is not specified, perform the following operations: (1 + 2) + 3) + 4)

If the initial parameter exists, perform the following operations: (10 + 1) + 2) + 3) + 4)

 

Note: A function cannot be set to None. A function must have two parameters.

 

V. zip Functions

Sorted () and zip () return a sequence (list) object, reversed (), enumerate () return an iterator (similar sequence)

Definition: zip ([seql,...]) take a series of iteratable objects as parameters, package the corresponding elements in the objects into tuple (tuples), and return a list composed of these tuples ). If the length of the input parameter is different, the returned list length is the same as the minimum length of the object in the parameter.

>>> List (zip ([, 3], [, 45, 2]) # The two lists have the same length.

[(1,213), (23, 45), (3, 2)]

>>> List (zip ([, 3], [, 54]) # The two lists are of different lengths, whichever is short.

[(1,213), (23, 45), (3, 2)]

 

 

Zip applications:

>>> [[I for I in range (3 * n + 1, 3 * n + 4)] for n in range (3)]

[1, 2, 3], [4, 5, 6], [7, 8, 9]

 

1. Two-dimensional matrix transformation (column-and-column interchange of matrices)

>>> A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]

>>> [[Row [col] for row in a] for col in range (len (a [0])]

[1, 4, 7], [2, 5, 8], [3, 6, 9]

>>> List (zip (* ))

[1, 4, 7], [2, 5, 8], [3, 6, 9]

>>> Map (list, zip (* ))

[1, 4, 7], [2, 5, 8], [3, 6, 9]

 

2. * The operator can work with the zip function to implement the opposite function. The merged sequence is split into multiple tuple.

>>>> X = [1, 2, 3], y = ['A', 'B', 'C']

>>>> Zip (* zip (x, y ))

[(1, 2, 3), ('A', 'B', 'C')]

 

3. Use zip to merge adjacent list items

>>> A = [1, 2, 3, 4, 5, 6]

>>> List (zip (* ([iter (a)] * 2 )))

[(1, 2), (3, 4), (5, 6)]

 

>>> Group_adjacent = lambda a, k: zip (* ([iter (a)] * k ))

>>> List (group_adjacent (a, 3 ))

[(1, 2, 3), (4, 5, 6)]

>>> List (group_adjacent (a, 2 ))

[(1, 2), (3, 4), (5, 6)]

>>> List (group_adjacent (a, 1 ))

[(1,), (2,), (3,), (4,), (5,), (6,)]

 

>>> List (zip (a [: 2], a [1: 2])

[(1, 2), (3, 4), (5, 6)]

 

>>> List (zip (a [: 3], a [1: 3], a [2: 3])

[(1, 2, 3), (4, 5, 6)]

 

>>> Group_adjacent = lambda a, k: zip (* (a [I: k] for I in range (k )))

>>> List (group_adjacent (a, 3 ))

[(1, 2, 3), (4, 5, 6)]

>>> List (group_adjacent (a, 2 ))

[(1, 2), (3, 4), (5, 6)]

>>> List (group_adjacent (a, 1 ))

[(1,), (2,), (3,), (4,), (5,), (6,)]

 

4. Use zip and iterators to generate a sliding window (n-grams)

>>> From itertools import islice

>>> Def n_grams (a, n ):

Z = (islice (a, I, None) for I in range (n ))

Return zip (* z)

>>> A = [1, 2, 3, 4, 5, 6]

>>> List (n_grams (a, 3 ))

[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]

>>> List (n_grams (a, 2 ))

[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]

>>> List (n_grams (a, 4 ))

[(1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6)]

 

5. Use zip to reverse the dictionary

>>> M = {'A': 1, 'B': 2, 'C': 3, 'D': 4}

>>> List (m. items ())

[('A', 1), ('C', 3), ('B', 2), ('D', 4)]

>>> List (zip (m. values (), m. keys ()))

[(1, 'A'), (3, 'C'), (2, 'B'), (4, 'D')]

>>> Dict (zip (m. values (), m. keys ()))

{1: 'A', 2: 'B', 3: 'C', 4: 'D '}

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.