Learning Python expression --lambda

  lambda expressions, anonymous functions to create

lambda <参数> : <返回值>

lambda expression1 : expression2
# 等价于
def func(expression1):
	return expression2

  Also it can be used to create nested functions

def func(x):
	return lambda a:a+x

f = func(5)
# 现在f是一个lambda对象
print(f(3))
# 8

  More layers can also be

def fun(a):
    return lambda b: lambda c: 100*a+10*b+c

f1 = fun(1)
f2 = f1(2)
print(f2(3))
# 123

application

  lambda characteristic, so that it can be built with Python map, reduce, filterfunctions to implement complex functions with a small amount of code, but also reflects the philosophy Python

  map () function to provide the functions may be iteratively processed data are respectively transmitted to the first parameter the second parameter

# 计算一个列表所有数字的平方
L = [1, 2, 3, 4, 5]
print(list(map(lambda x: x * x, L)))
# [1, 4, 9, 16, 25]

  reduce () function receives the same parameter types and map function, but the function to receive two parameters, can perform the entire nested iteration data

redece(fun,[1,2,3,4]) = fun(fun(fun(1,2),3),4)
# 计算整个列表的积
L = [1, 2, 3, 4, 5]
print(reduce(lambda a, b: a * b, L))
# 15

  filter () function is used to screen, perform the function of the first parameter value within a second parameter, leaving the true

# 筛选整个列表内3的倍数
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(filter(lambda x: not x % 3, L)))
# [3, 6, 9]
Published 28 original articles · won praise 8 · views 2787

Guess you like

Origin blog.csdn.net/IuSpet/article/details/104117908
Recommended