python開發函數進階:匿名函數

來源:互聯網
上載者:User

標籤:運行   lte   列表   函數   span   查詢   zip   內容   產生   

一,匿名函數

#簡單的需要用函數去解決的問題 匿名函數的函數體 只有一行
#也叫lambda運算式
# cal2(函數名) = lambda n(參數) : n*n(參數怎麼處理,並且傳回值)
#參數可以有多個,用逗號隔開
#匿名函數不管邏輯多複雜,只能寫一行,且邏輯執行結束後的內容就是傳回值
#傳回值和正常的函數一樣可以是任意資料類型
1.函數和匿名函數

 1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3  4 def cal(n): 5     return n*n 6 print(cal(10)) 7 cal2 = lambda n:n*n 8 print(cal2(10)) 9 10 def add(x,y):11     return x+y12 print(add(1,2))13 add2 = lambda x,y : x+y14 print(add2(1,2))15 16 #尋找大於10的數字17 l = [10,11,8,12]18 def func(x):19     return x>1020 print(list(filter(func,l)))21 print(list(filter(lambda x:x>10,l)))22 23 #數字冪次方運算24 def pow2(x):25     return x*x26 map(pow2,l)27 print(list(map(lambda x:x*x , l)))

 

2.匿名函數真的可以匿名,在和其他函數合作的時候

 1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3  4 #查詢字典Value值最大的 5 dic={‘k1‘:10,‘k2‘:100,‘k3‘:30} 6 print(max(dic))    #K3 7 func = lambda k:dic[k]  #values 8 print(max(dic,key = func)) 9 print(max(dic,key = lambda k:dic[k]))10 #運行邏輯   dic >> lambda >> max >> key      #模糊11 12 13 #現有兩個元組((‘a‘),(‘b‘)),((‘c‘),(‘d‘)),請使用python中匿名函數產生列表[{‘a‘:‘c‘},{‘b‘:‘d‘}]14 #第一種15 t1 = ((‘a‘),(‘b‘))16 t2 = ((‘c‘),(‘d‘))17 print(list(zip(t1,t2)))   #[(‘a‘, ‘c‘), (‘b‘, ‘d‘)]18 print(list(map(lambda t:{t[0]:t[1]} ,zip(t1,t2))))  #zip拉鏈成列表 map有解壓法19 20 #第二種21 print([{i:j} for i,j in zip(t1,t2)])  #item = (‘a‘, ‘c‘)  i,j = ‘a‘, ‘c‘  元祖的解包22 func = lambda t1,t2 : [{i:j} for i,j in zip(t1,t2)]  #右邊是傳回值23 ret = func(t1,t2)24 print(ret)

 

python開發函數進階:匿名函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.