lambda函数的用法简记

时间:2021-09-06 21:09:10

lambda函数

lambda是一个匿名函数,其语法为:lambda parameters:express

一般用法

import numpy as np
sigmoid = lambda x:1./(1.+np.exp(-x))
sigmoid(np.array([-10, 0, 10]))
array([  4.53978687e-05,   5.00000000e-01,   9.99954602e-01])

条件语句:express1 if condition else express2

# express1 if condition else express2 
color_map = lambda x:'red' if x == 1 else 'blue'
print(color_map(1))
print(color_map(0))
red
blue

对字典按照value排序

# example 3
d = {'b':3, 'a':7, 'd':1, 'c':5}
print('d =',d)
print(sorted(d.values(), reverse = True))
print(sorted(d.items(), key = lambda x:x[1], reverse = False))
print(sorted(d.items(), key = lambda x:x[0], reverse = False))
d = {'b': 3, 'a': 7, 'd': 1, 'c': 5}
[7, 5, 3, 1]
[('d', 1), ('b', 3), ('c', 5), ('a', 7)]
[('a', 7), ('b', 3), ('c', 5), ('d', 1)]

复杂一点的用法

# computing the AUC
y_pred = np.array([1, 0, 0, 0, 1, 1, 0])
y_true = np.array([1, 0, 1, 0, 0, 1, 0])
# [(lambda x:1 if x == True else 0)(res) for res in y_pred==y_true]
print('Accuracy %d%%' % ((np.sum([(lambda x:1 if x==True else 0)(res) for res in y_pred==y_true]))/y_true.shape[0]*100))
Accuracy 71%

使用lambda进行函数的传递

def print_mm(para):
for x in para:
print('-'*10, str(x*2), '-'*10)

def fun(model):
a = np.arange(10) # 想在本函数的数据a上使用函数predict,就可以将函数predict作为参数传递过来
model(a)

fun(lambda x:print_mm(x))
---------- 0 ----------
---------- 2 ----------
---------- 4 ----------
---------- 6 ----------
---------- 8 ----------
---------- 10 ----------
---------- 12 ----------
---------- 14 ----------
---------- 16 ----------
---------- 18 ----------