1. lambda表达式
又称为匿名函数。格式:
lambda 参数列表:函数体
例1:
实现一个简单的两数相加的方法,如下:
def add(x, y): return x + y
使用lambda表达式实现两数相加,如下:
add_lambda = lambda x,y: x+y
调用的方法:
res = add_lambda(2,3) print('res:', res)
结果:
res: 5
2. 三元运算符
格式:
结果1 if 条件 else 结果2
当条件为True时,返回结果1;条件为False时,返回结果2。
例1:
condition = True res = 1 if condition else 2 print('res:', res)
结果:
res: 1
例2:
condition = False res = 1 if condition else 2 print('res:', res)
结果:
res: 2
3. map函数
例1:
list1 = [1, 2, 3, 4, 5] res = map(lambda x: x + x, list1) print(list(res))
结果:
[2, 4, 6, 8, 10]
例2:
list1 = [1, 2, 3, 4, 5] list2 = [1, 2, 3, 4, 5] res = map(lambda x, y: x*x + y, list1, list2) print(list(res))
结果:
[2, 6, 12, 20, 30]
4. filter过滤器
例1:
def is_not_none(s): return s and len(s.strip())>0 list1 = [' ', 'tree', 'filter', None, ''] res = filter(is_not_none, list1) print(list(res))
结果:
['tree', 'filter']
5. reduce函数
reduce函数将当前的计算结果代入下一次计算。,
例1:
from functools import reduce list1 = [1, 2, 3, 4, 5] fun = lambda x, y : x + y res = reduce(fun, list1) print(res)
结果:
15
例2:
第三个参数是初始值。
from functools import reduce list1 = [1, 2, 3, 4, 5] fun = lambda x, y : x + y res = reduce(fun, list1, 10) print(res)
结果:
25