python匿名函数Lambda的两种用法
一般来说匿名函数Lambda的使用就是为了避免单独def一个函数,而且不用给函数命名,但是其表达式只能有一行,相当于def函数只有一行return。匿名函数也是一个函数对象,其用法有以下两种:
第一种方式:作为函数对象单独使用
calc=lambda x, y: x ** y # 函数定义
calc(1,2) # x = 1, y = 2,计算1的平方
第二种方式:放在另一函数里使用
list = [1, 2, 3, 4]
map(lambda x: x ** 2,list)
这种函数的特点是函数的输入有函数对象,有变量,变量作为函数对象的输入。
另例初中方法近似求函数3x2 + 2x + 1在x = 2的导数:
def aprx_der(f, x, eps):
return (f(x + eps) - f(x - eps) / (2. * eps)
val = aprx_der(lambda x: 3 * x ** 2 + 2 * x + 1, 2, 1e-3)
lambda引用其他函数也是可以的
等价写法:
def g(x):
return 3 * x ** 2 + 2 * x
val = aprx_der(lambda x: g(x) + 1, 2, 1e-3)
另例:
import tensorflow as tf
dataset = tf.data.Dataset.range(1, 6) # [ 1, 2, 3, 4, 5 ]
dataset2=dataset.interleave(lambda x: tf.data.Dataset.from_tensors(x).repeat(6),
cycle_length=2, block_length=4)
for item in dataset2:
print(item.numpy(),end=', ')
Result:
1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5,