python中lambda的用法

2025-12-01 0 34,511

对于一个函数,只有一句话表示,那么就可以用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
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 python中lambda的用法 https://www.zhiup.top/4864.html

相关