python中lambda的用法
2024-08-01
来源:骅佗教育
对于一个函数,只有一句话表示,那么就可以用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