Python 匿名函数


不定义函数名的函数。
lambda 表达式:

lambda parameter_list: expression
1
例:

def add(x, y):
    return x + y

add(1, 2)

# 等同于:
f = lambda x,y: x+y
f(1, 2)
1
2
3
4
5
6
7
8
三元表达式:

条件为真时返回的结果 if 条件判断 else 条件为假时的返回结果
1
例:

x = 2
y = 1
r = x if x > y else y
print(r)    # 返回:2
1
2
3
4
map 类:

把一个集合里的元素映射到新的集合里。
list_x = [1,2,3]

def square(x):
    return x * x

r = map(square, list_x)
# 等同于:
#for x in list_x:
#   square(x)

print(list(r))    # 返回:[1,4,9]
1
2
3
4
5
6
7
8
9
10
11
list_x = [1,2,3]
r = map(lambda x: x*x, list_x)
print(list(r))    # 返回:[1,4,9]
1
2
3
list_x = [1,2,3,4,5]
list_y = [1,2,3]
r = map(lambda x,y: x*x+y, list_x, list_y)
print(list(r))    # 返回:[2,6,12]
1
2
3
4
reduce 函数:

连续计算,连续调用 lambda,每一次的计算结果作为下一次计算的参数。
from functools import reduce

list_x = [1,2,3,4]
r = reduce(lambda x,y: x+y, list_x)
print(r)    # 返回:10
# ((1+2)+3)+4

r = reduce(lambda x,y: x+y, list_x, 10)  # 10为初始值
print(r)    # 返回:20
# (((10+1)+2)+3)+4
1
2
3
4
5
6
7
8
9
10
filter 类:

过滤器
list_x = [1,0,1,0,0,1]
filter(lambda x: True if x==1 else False, list_x)
print(list(r))    # 返回:[1,1,1]
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值