Several important functions of Python (lambda,filter,reduce,map,zip)

Source: Internet
Author: User
Tags iterable

one, anonymous function lambda

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

1, Lambda is an expression, not a statement.

Because of this, Lambda can appear where the DEF is not allowed in the Python syntax---for example, in a list constant or in a parameter called by a function, and as an expression, lambda returns a value (a new Function) that can optionally be given a variable Name. instead, The DEF statement always assigns a new function to a variable name at the head, rather than returning the function as a result.

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

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

Example:

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

>>>f (2,3,4)

9

>>>x= (lambda a= "fee", b= "fie", c= "foe": a+b+c)

>>>x ("wee")

' Weefiefoe '

You usually use lambda to write a jump table, as Follows:

>>>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, as Follows:

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

second, map function

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

As you can see by definition, the first parameter of this function is a function, the remaining argument is one or more sequences, and the return value is an Iterator.

Function can be understood as a one-to-one or many-to-a function, the role of map is to call the function function as each element in the parameter sequence, and return the iterator containing the return value of each Function.

Returns an iterative object that requires a list call to display all Results.

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

[3, 4, 5]

>>>list (map (pow,[1,2,3],[2,3,4))

[1,8,81]

third, the filter function

The filter function performs a filtering operation on the specified sequence.

The definition of the filter function:

Filter (function or None, sequence)->iterator

The filter function calls the function function for each element in the sequence parameter sequence, and the result that is returned contains the element that invokes the result to True.

Returns an iterative object that requires a list call to display all Results.

>>>list (filter (lambda x:x>0), Range ( -5,5))

[1,2,3,4]

>>>list (filter (none,range ( -5,5)))

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

If function is none, an iterator that contains a non-empty element is Returned.

four, Reduce function

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

Definition of the reduce function:

Functools.reduce (function, iterable[, initializer]) #python3中reduce是在functools模块中

The function parameter is a two-parameter, and reduce sequentially takes an element from iterable and invokes function again with the result of the last call to Function.

The first call to function, if supplied with the initial parameter, calls function with the first element in iterable and initial as a parameter, otherwise the function is invoked with the first two elements in the Iterable.

Equivalent to:

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,3,4])

10

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

20

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

24

If there is no initial parameter, this is calculated as: ((((1+2) +3) +4)

If there is a initial parameter, this is calculated as: ((((((10+1) +2) +3) +4)

note: function functions cannot be none,function must be functions with 2 Parameters.

five, zip function

Where sorted () and zip () return a sequence (list) object, reversed (), Enumerate () returns an iterator (similar to a Sequence)

Definition: Zip ([seql, ...]) Accepts a series of iterative objects as parameters, packages the corresponding elements in the object into tuple (tuples), and then returns a list of these tuples (lists). If the length of the passed parameter is not equal, the length of the returned list is the same as the object with the shortest length in the Parameter.

>>> list (zip ([1,23,3],[213,45,2])) #两个列表长度一致

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

>>> list (zip ([1,23,3],[213,45,2,34,54])) #两个列表长度不一致, whichever is shorter

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

Zip some applications:

>>> [[i-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 (matrix of the row and column Interchange)

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

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

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

>>>list (zip (*a))

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

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

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

2, * operator and zip function can be used in conjunction with the zip functions, the merging sequence is split into multiple tuple

>>>>x=[1,2,3],y=[' a ', ' b ', ' C ']

>>>>zip (*zip (x, Y))

[(a), (' 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. Using zip and iterators to generate 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. Using the zip inversion 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 '}

Several important functions of Python (lambda,filter,reduce,map,zip)

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.