python中lambda的用法
【摘要】对于一个函数,只有一句话表示,那么就可以用lambda表达式表示,如:deff(x): returnx*x print(f(5))out:25可以写为:f=lambdax:x*x 冒号左
对于一个函数,只有一句话表示,那么就可以用lambda表达式表示,如:
def f(x):
return x * x
print(f(5))
out: 25
可以写为:
f = lambda x: x*x # 冒号左边为输入,右边是返回值,f是函数名
print(f(5))
out: 25
对于多个形式参数:
g = lambda x,y: x+y # 冒号左边为输入,右边是返回值,f是函数名
print(g(4,5))
out: 9
lambda用到比较多的地方是排序,如:
def get_four(my):
return my[2]
tuple_my = []
file = open("file.csv", "r")
for line in file:
Line = line.strip()
arr = line.split(",")
one = arr[1]
three = arr[3]
four = int(arr[4])
tuple_my.append( (one, three, four) )
tuple_my.sort(key=get_four)
for my in tuple_my:
print(my)
可以写为:
get_four = lambda my: my[2]
tuple_my = []
file = open("file.csv", "r")
for line in file:
Line = line.strip()
arr = line.split(",")
one = arr[1]
three = arr[3]
four = int(arr[4])
tuple_my.append( (one, three, four) )
tuple_my.sort(key=get_four)
for my in tuple_my:
print(my)
tuple_my = []
file = open("file.csv", "r")
for line in file:
Line = line.strip()
arr = line.split(",")
one = arr[1]
three = arr[3]
four = int(arr[4])
tuple_my.append( (one, three, four) )
tuple_my.sort(key=lambda my: my[2])
for my in tuple_my:
print(my)
lambda也经常用在符合函数下,如:
def quadratic(a, b, c):
return lambda x: a*x*x*x + b*x*x + c*x
f = quadratic(3, -2, 4)
print(f(5))
345
def quadratic(a, b, c):
return lambda x: a*x*x*x + b*x*x + c*x
print(quadratic(3, -2, 4)(5))
345
上一篇:python入门基础教程
下一篇:python中的赋值方法
就业培训申请领取
环球青藤
官方QQ群扫描上方二维码或点击一键加群,免费领取大礼包,加群暗号:青藤。 一键加群
最新文章
Python编程各地入口
环球青藤官方微信服务平台
刷题看课 APP下载
免费直播 一键购课
代报名等人工服务
Python编程热点排行