python中lambda、filter、map、reduce的用法
lambda
# lambda可以理解为一个匿名函数,或者快速定义一个函数
# lambda 并不会带来程序运行效率的提高,只会使代码更简洁。
# 举例:
double = lambda x:x*2
print(double(18)) # 得到36
plus = lambda a,b:a+b
print(plus(10,5)) # 得到15
filter
# 功能:实现对list的过滤
# 用法 filter(func,list) # 第一个参数为函数 返回布尔值 第二个参数为迭代器
# 最终返回一个filter对象,可转化为list
# 举例,结合lambda实现列表过滤
>>> number_list = [1,3,4,6,8,9]
>>> new_list = filter(lambda x:x % 2 == 0, number_list)
>>> print(new_list)
<filter object at 0x0000020346A1EE88>
>>> list(new_list)
[4, 6, 8]
map
# 功能:map()方法会将 一个函数 映射到序列的每一个元素上,生成新序列,包含所有函数返回值。
# 实际也并不会比普通for循环高效很多
# 用法:
map(function_to_apply, list_of_inputs)
# function_to_apply:代表函数
# list_of_inputs:代表输入序列
# 举例:
items = [1, 2, 3, 4, 5]
list(map(lambda x: x**2, items))
reduce
- reduce的工作过程是 :在迭代序列的过程中,首先把 前两个元素(只能两个)传给 函数,函数加工后,然后把 得到的结果和第三个元素 作为两个参数传给函数参数, 函数加工后得到的结果又和第四个元素 作为两个参数传给函数参数,依次类推。
# 用法
reduce(function, iterable[, initializer])
# function:代表函数
# iterable:序列
# initializer:初始值(可选)
# 举例 1到10的阶乘
# 导入reduce
from functools import reduce
# 定义函数
def f(x,y):
return x*y
# 定义序列,含1~10的元素
items = range(1,11)
# 使用reduce方法
result = reduce(f,items)
print(result)
# 举例字符串拼接
from functools import reduce
str_list = ["aaa","bbb","ccc","ddddd"]
new_str = reduce(lambda a,b:str(a+b),str_list)
print(new_str)
# 结果:aaabbbcccddddd