python中lambda的用法是什么-创新互联
创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!
目前创新互联已为上1000家的企业提供了网站建设、域名、网站空间、网站托管运营、企业网站设计、都安网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。小编给大家分享一下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的用法是什么有了一定的了解,想了解更多相关知识,欢迎关注创新互联-成都网站建设公司行业资讯频道,感谢各位的阅读!
网页标题:python中lambda的用法是什么-创新互联
标题路径:http://cdiso.cn/article/csdcje.html