Python lambda expression simple usage

Source: Internet
Author: User
Tags define function

12345678 # General conditions Statement if   1 = = 1:      name =  ' Wupeiqi ' else : &NBSP;&NBSP;&NBSP;&NBSP; name =  ' Alex '    # ternary operations ' Wupeiqi '  if  < Code class= "Bash plain" >1 = = 1  else  

For simple functions, there is also an easy way to express that: lambda expression

123456789101112131415 # ######### ############# normal function ###################### # define function (Normal mode) def func (ARG): &NBSP;&NBSP;&NBSP;&NBSP; return  arg + 1    # execute function result = func (123) Code class= "Bash Spaces" >   # ###################### Lambda ########### ###########    # define function (lambda expression) my_lambda = lambda Arg:arg + 1    < Code class= "Bash comments" ># execute function result = MY_LAMBDA (123)

The existence of Lambda means a concise representation of simple functions

Built-in function two

First, Map

Iterates through the sequence, operates on each element of the sequence, and finally gets a new sequence.

Li = [one, one, 33]new_list = map (lambda a:a + li)
Li = [one, 33]SL = [1, 2, 3]new_list = map (lambda A, b:a + B, Li, SL)

Second, filter

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

Li = [one, one, 33]new_list = filter (lambda arg:arg > P, li) #filter第一个参数为空, the original sequence will be obtained

Third, reduce

Cumulative operation for all elements within a sequence

Li = [one, three, 33]result = reduce (lambda arg1, Arg2:arg1 + Arg2, Li) # The first argument of reduce, the function must have two parameters # reduce the second parameter, to loop the sequence # reduce The third parameter, the initial value

Python lambda expression simple usage

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.