新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python中l(wèi)ambda的用法
對于一個函數(shù),只有一句話表示,那么就可以用lambda表達式表示,如:

def f(x): return x * x print(f(5))
out: 25
可以寫為:
f = lambda x: x*x # 冒號左邊為輸入,右邊是返回值,f是函數(shù)名 print(f(5))
out: 25
對于多個形式參數(shù):
g = lambda x,y: x+y # 冒號左邊為輸入,右邊是返回值,f是函數(shù)名 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也經(jīng)常用在符合函數(shù)下,如:
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
當(dāng)前題目:創(chuàng)新互聯(lián)Python教程:python中l(wèi)ambda的用法
URL網(wǎng)址:http://m.fisionsoft.com.cn/article/dhcejpj.html


咨詢
建站咨詢
