Lambda, map, filter, and reduce for Python functions

Source: Internet
Author: User

1. Lambda function

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

Lambda [arg1[, Arg2, ... ArgN]: expression

When learning conditional operations, for simple if else statements, you can use the ternary operation to indicate that:

# Common conditional Statements if 1 = =1    :'evescn'else    :' GM '  # Ternary Operations ' EVESCN ' if Else ' GM '

For simple functions, there is also an easy way to represent a lambda expression

# ###################### Common function ###################### # defining functions (normal way) def func (ARG):     return arg + 1  #  execution function result = func (123)  #  ######## ############## Lambda ######################  #  definition function (lambda expression)Lambda Arg:arg + 1  #  execution function result = MY_LAMBDA (123)

Lambda existence means a concise representation of a simple function, as in the example of a list below

L = [One, one, ten, x:x = map (lambda + = List (new_l)print(a)#  Output Results [21, 32, 43, 54]

2. Map functionThe map function maps the specified sequence according to the provided function. definition of the map function:

The map function invokes the function function for each element in the sequence parameter sequence, returning the result of invoking the return value of the function functions for each element

L = [One, one, one, ten]def  myadd (x):    return x + ten== List (new _n)print(b)#  Output Results [21, 32, 43, 54]

The use map() of functions, the user entered the non-standard English name, the first letter capitalized, other lowercase canonical name. Input: [‘adam‘, ‘LISA‘, ‘barT‘] , output: [‘Adam‘, ‘Lisa‘, ‘Bart‘] :

3. Filter function

Filter the elements in a sequence, and finally get a sequence that matches the criteria

def myfunc (x):     if x >:        return  True    Else:        return = [ One, one, one== = List (new_a)print(b)#    Output result [33]

4. Reduce function

Cumulative operation for all elements within a sequence

reduceA function that acts on a sequence [x1, x2, x3, ...], this function must receive two parameters, reduceThe result continues and the next element of the sequence is accumulated, and the effect is:
Reduce (f, [X1, x2, X3, x4]) = f (f (f (x1, x2), x3), x4)

For example, to sum a sequence, it can be reduce implemented by:

 from Import Reduce def Add (x, y): ...      return x + y ... >>> reduce (add, [1, 3, 5, 7, 9])25

Of course, the sum operation can be directly built into Python functions sum() , no need to use reduce .

But if you want to [1, 3, 5, 7, 9] transform the sequence into integers 13579 , you can put reduce it in handy:

 from Import Reduce def fn (x, y): ...      return x * ten + y ... >>> reduce (FN, [1, 3, 5, 7, 9])13579

This example is not very useful in itself, but if we consider that the string str is also a sequence, with a slight change to the above example, map() we can write the str converted int function:

>>> fromFunctoolsImportReduce>>>deffn (x, y): ...returnX * 10 +y ...>>>defChar2num (s): ...return{'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9'8 {}[s] ...>>> reduce (FN, map (Char2num,'13579'))13579

str2intthe function that is organized into one is:

 fromFunctoolsImportReducedefStr2Int (s):deffn (x, y):returnX * 10 +ydefChar2num (s):return{'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9}[s]returnReduce (FN, map (Char2num, s))

You can also use lambda functions to further simplify:

 fromFunctoolsImportReducedefChar2num (s):return{'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9}[s]defStr2Int (s):returnReduceLambdaX, y:x * + y, map (Char2num, s))

That is, assuming that Python does not provide a int() function, you can write a function that converts the string to an integer by itself, and only requires a few lines of code!

Reprinted from: Https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 0014317852443934a86aa5bb5ea47fbbd5f35282b331335000

Http://www.cnblogs.com/wupeiqi/articles/4943406.html

Lambda, map, filter, and reduce for Python functions

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.