知行编程网知行编程网  2023-01-11 18:30 知行编程网 隐藏边栏  10 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python中lambda的用法的相关知识,包括python中lambda和map,以及用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

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享