匿名函数 (基本定义):
#匿名函数
def add(x, y):
return x + y
# lambda parameter_list : expression #: 后面不可以是 表达式 如: a = x + y
print(add(1,2))
f = lambda x ,y : x + y #匿名函数方式
print(f(1,2))
结果:
3
3
三元表达式:
# 条件为真时返回的结果 if 条件判断 else 条件为假时的返回结果
r = x if x > y else y # r 获取结果
map 定义
map -> class map(func,*iterables)
基本使用(以集合的形式映射,而结果跟使用的函数有关):
#map
# map -> class map(func,*iterables)
list_x = [1,2,3,4,5]
# [1, 4, 9, 16, 25]
def aquare(x)
return x * x
r = map(aquare,list_x)
print(list(r))
结果:
[1, 4, 9, 16, 25]
结合匿名函数使用:
r = map(lambda x : x * x , list_x)
print(list(r)
多值的使用 map
list_x = [1,2,3,4,5]
list_y = [1,2,3,4,5]
r = map(lambda x : x * x , list_x)
r1 = map(lambda x,y : x * x + y, list_x,list_y)
print(list(r))
print(list(r1))
结果:
[1, 4, 9, 16, 25]
[2, 6, 12, 20, 30]
reduce (归约):
基本定义使用:
list_x = [1,2,3,4,5]
list_y = [1,2,3,4,5]
from functools import reduce
#连续计算,连续调用lambda
r = reduce(lambda x,y: x * y,list_x) # lambda 一定要有两个参数
print(r)
结果:
120
filter(剔除):
基本使用定义:
# filter 剔除相同元素
list_x = [0,1,0,0,0,1]
r = filter(lambda x: True if x == 1 else False, list_x)
print(list(r))
结果:
[1, 1]