Python Development function Advanced: anonymous function

Source: Internet
Author: User

One, anonymous function

The function body of #简单的需要用函数去解决的问题 anonymous function has only one row
#也叫lambda表达式
# cal2 (function name) = Lambda N (parameter): n*n (parameter how to handle and return value)
#参数可以有多个, separated by commas
#匿名函数不管逻辑多复杂, only one line can be written, and the content after the end of the logical execution is the return value
#返回值和正常的函数一样可以是任意数据类型
1. Functions and anonymous functions

1 #!/usr/bin/env python2 #_*_coding:utf-8_*_3 4 defcal (n):5     returnNN6 Print(Cal (10))7Cal2 =Lambdan:n*N8 Print(Cal2 (10))9 Ten defAdd (x, y): One     returnx+y A Print(Add ()) -ADD2 =Lambdax,y:x+y - Print(ADD2 ()) the  - #find a number greater than 10 -L = [10,11,8,12] - deffunc (x): +     returnX>10 - Print(List (filter (func,l))) + Print(List (Filter (LambdaX:x>10, L))) A  at #Digital Power-order operation - defpow2 (x): -     returnx*x - map (pow2,l) - Print(List (Map (LambdaX:x*x, L)))

2. Anonymous functions can really be anonymous, when working with other functions

1 #!/usr/bin/env python2 #_*_coding:utf-8_*_3 4 #Query dictionary value of the largest value5dic={'K1': 10,'K2': 100,'K3': 30}6 Print(Max (DIC))#K37Func =LambdaK:DIC[K]#Values8 Print(max (Dic,key =func))9 Print(max (Dic,key =LambdaK:dic[k]))Ten #run logic dic >> Lambda >> max >> key #模糊 One  A  - #existing two tuples ((' A '), (' B ')), ((' C '), (' d ')), use the anonymous function in Python to generate the list [{' A ': ' C '},{' B ': ' d '}] - #First Kind theT1 = (('a'),('b')) -T2 = (('C'),('D')) - Print(List (Zip (t1,t2)))#[(' A ', ' C '), (' B ', ' d ')] - Print(List (Map (LambdaT:{T[0]:T[1]}, Zip (T1,T2))))#zip zip into List map with decompression method +  - #The second Kind + Print([{I:j} forI,jinchZip (t1,t2)])#item = (' A ', ' C ') i,j = ' A ', ' C ' progenitor's unpacking AFunc =LambdaT1,t2: [{i:j} forI,jinchZip (T1,T2)]#To the right is the return value atRET =func (T1,T2) - Print(ret)

Python Development function Advanced: anonymous function

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.