小编给大家分享一下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
看完了这篇文章,相信你对python中lambda的用法是什么有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。