Python's lambda

Source: Internet
Author: User

If else can be represented by a simple ternary operator

If 1 = = 1:    name = ' Wupeiqi ' else:    name = ' Alex '

--》

name = ' Wupeiqi ' if 1 = = 1 Else ' Alex '

Lambda can also be used to simplify expressions for functions

# ###################### normal function ####################### definition function (normal way) def func (Arg):    return arg + 1  # Execute function result = Func (123)  # ###################### Lambda ######################  # definition function (lambda expression) My_lambda = lambda Arg:arg + 1  # Execute function Res Ult = MY_LAMBDA (123)
Built-in function 1,map

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

Li = [one, one, 33]new_list1 = map (lambda a:a + li) Print new_list1

[111, 122, 133]

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

[23, 46, 69]

2,filter

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

Li = [one, one, 33]new_list2 = filter (lambda arg:arg >=, li) print new_list2

[22, 33]

3,reduce

Cumulative operation for all elements within a sequence

Li = [one, 33]SL = [1, 2, 3]result = reduce (lambda arg1, Arg2:arg1 + arg2, li) print result
# Reduce the first argument, the function must have two parameters # reduce the second parameter, to loop the sequence # reduce the third parameter, the initial value

66

Python's lambda

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.