欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > python中lambda的用法

python中lambda的用法

2026/5/2 6:51:13 来源:https://blog.csdn.net/hakesashou/article/details/144935363  浏览:    关键词:python中lambda的用法

对于一个函数,只有一句话表示,那么就可以用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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词