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

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值