Python匿名函數---lambda

lambda函數

lambda 是一種簡潔格式的函數,此表達式不是正常的函數結構,而是屬於表達式的類型
lambda  能夠使用判斷語句,而且必須有else語句,但是不能有多項分支,只能用單項分支
功能:lambda 參數1 參數2...: 函數功能代碼
res = lambda x,y:x+y
print(res(1,2))



F:\學習代碼\Python代碼\venv\Scripts\python.exe F:/學習代碼/Python代碼/day6/匿名函數---lambda.py
3

Process finished with exit code 0
L = ["1","2","3","5","7","8","4","9","6"]
#求列表中所有偶數組成的最大整數
#求列表中所有奇數組成的最小整數
from functools import reduce

L = ["1","2","3","5","7","8","4","9","6"]
#求列表中所有偶數組成的最大整數
#求列表中所有奇數組成的最小整數
res = map(int,L)
#先對數據進行篩選
var = filter(lambda x:True if x%2 == 0 else False,res)
#然後對數據進行排序
val = sorted(var,reverse=True)
#對數據進行整合,求最大整數
def func(a,b):
    return a*10 + b
result = reduce(func,val)
print(result)



F:\學習代碼\Python代碼\venv\Scripts\python.exe F:/學習代碼/Python代碼/day6/匿名函數---lambda.py
8642

Process finished with exit code 0
from functools import reduce

L = ["1","2","3","5","7","8","4","9","6"]
#求列表中所有奇數組成的最小整數
res = map(int,L)
#先對數據進行篩選
var = filter(lambda x:True if x%2 == 1 else False,res)
#然後對數據進行排序
val = sorted(var)
#對數據進行整合,求最大整數
def func(a,b):
    return a*10 + b
result = reduce(func,val)
print(result)




F:\學習代碼\Python代碼\venv\Scripts\python.exe F:/學習代碼/Python代碼/day6/匿名函數---lambda.py
13579

Process finished with exit code 0

使用一行代碼求上列兩個問題:

from functools import reduce

res = reduce(lambda x,y:x*10+y,sorted(filter(lambda x:True if x%2==0 else False,map(int,L))),reverse=True)
print(res)

res = reduce(lambda x,y:x*10+y,sorted(filter(lambda x:True if x%2==1 else False,map(int,L))))
print(res)




F:\學習代碼\Python代碼\venv\Scripts\python.exe F:/學習代碼/Python代碼/day6/匿名函數---lambda.py
8642
13579

Process finished with exit code 0

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章