掃二維碼與項(xiàng)目經(jīng)理溝通
我們?cè)谖⑿派?4小時(shí)期待你的聲音
解答本文疑問/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
對(duì)于一個(gè)函數(shù),只有一句話表示,那么就可以用lambda表達(dá)式表示,如:

def f(x): return x * x print(f(5))
out: 25
可以寫為:
f = lambda x: x*x # 冒號(hào)左邊為輸入,右邊是返回值,f是函數(shù)名 print(f(5))
out: 25
對(duì)于多個(gè)形式參數(shù):
g = lambda x,y: x+y # 冒號(hào)左邊為輸入,右邊是返回值,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

我們?cè)谖⑿派?4小時(shí)期待你的聲音
解答本文疑問/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流