不定义函数名的函数。
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]