python中map与reduce
'''
map(func,*iterable)
参数1: func 指的是参数都需要执行的函数
参数2: 可迭代对象(可以for循环遍历的),都需要执行参数1函数的序列
作用:将参数2中的每个数据依次取出来执行参数1,得到执行后的结果
'''
#案例:将[1,2,3,4,5] --->["1","2","3","4","5"]
list1 = [1,2,3,4,5,6] res = map(str,list1) print(res) print(type(res)) print(list(res))
# 自定义一个map函数 def myMap(func,iterable): listRes = [] for i in iterable: res = func(i) listRes.append(res) return listRes listData = ["1","2","3","4","5","6"] res = map(int,listData) 用map内置函数打印 print(list(res)) res = myMap(int,listData) #用定义的函数打印 print(res)
'''
reduce 不是内置函数,需要通过 from functools import reduce导入才可以使用
reduce(func,sque)
参数func 该函数表示了聚合的方式
参数func需要传入两个参数,reduce会将func的执行结果继续和下一个数据进行运算,再得到最终的结果
参数sque 需要用来聚合的多个参数的序列
'''
#案例:计算1-100之间整数的和
from functools import reduce #先导入reduce模块 def add(a,b): #定义func函数 return a+b listData = range(1,101) res = reduce(add,listData) print(res)
# 练习: "456525446" ---> 456525446 from functools import reduce def fun(a,b): c = int(a)*10+int(b) return c str1 = "45652544665534" res = reduce(fun,str1) print(res)