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

猜你喜欢

转载自blog.csdn.net/qq_41112887/article/details/88767718