极客小将

您现在的位置是:首页 » python编程资讯

资讯内容

python中lambda的用法

极客小将2020-12-02-
简介对于一个函数,只有一句话表示,那么就可以用lambda表达式表示,如:def f(x):return x * xprint(f(5))out: 25可以写为:f = lambda x: x*x #&n

对于一个函数,只有一句话表示,那么就可以用lambda表达式表示,如:VG4少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

def f(x): return x * x print(f(5))out: 25

可以写为:VG4少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

f = lambda x: x*x # 冒号左边为输入,右边是返回值,f是函数名 print(f(5))out: 25

对于多个形式参数:VG4少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

g = lambda x,y: x+y # 冒号左边为输入,右边是返回值,f是函数名 print(g(4,5))out: 9

lambda用到比较多的地方是排序,如:VG4少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

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)

可以写为:VG4少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

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也经常用在符合函数下,如:VG4少儿编程网-Scratch_Python_教程_免费儿童编程学习平台

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))345def quadratic(a, b, c): return lambda x: a*x*x*x + b*x*x + c*x print(quadratic(3, -2, 4)(5))345

网友点评

共有5条评论来说两句吧...

在线客服