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

def f(x): return x * x print(f(5))
out: 25
可以寫(xiě)為:
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)可以寫(xiě)為:
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
標(biāo)題名稱(chēng):創(chuàng)新互聯(lián)Python教程:python中l(wèi)ambda的用法
新聞來(lái)源:http://m.5511xx.com/article/dhcejpj.html


咨詢
建站咨詢
