python的filter()、map()、reduce()函数测试
filter函数测试:过滤出奇数
mylist=[n for n in range(0,10)]
new_list = list(filter(lambda x:(x%2==1),mylist))
print(f"{type(new_list)}")
print('new_list=',new_list)
map函数测试:计算每个列表元素的平方
mylist=[n for n in range(0,10)]
new_list = list(map(lambda x:x**2,mylist))
print(f"{type(new_list)}")
print('new_list=',new_list)
reduce函数的测试
功能:用于对序列进行累积操作(如累加、累乘等),最终返回一个单一值。
语法(在 Python 3 中需要从 functools 模块导入):
最简测试
from functools import reduce
total=reduce(lambda x,y:x+y, [1,2,3,4,5])
print(total)
计算和的lambda表达式
f = lambda x,y:x+y
print(f(1,2))
输出结果是3
使用reduce计算列表中所有数的和
from functools import reduce
mylist=[n for n in range(0,10)]
total = reduce(lambda x,y:x+y,mylist)
print(f"{type(total)}")
print('total=',total)
使用reduce计算列表中所有偶数的和
from functools import reduce
mylist=[n for n in range(0,10)]
total = reduce(lambda x,y:x+y,list(filter(lambda x :(x%2==0),mylist)))
print(f"{type(total)}")
print('total=',total)
逐次递减:函数参数的次序问题
测试目的,函数执行的结果总是作为函数下次迭代的第一个参数。
from functools import reduce
mylist=[n for n in range(0,10)]
total = reduce(lambda x,y:x+y,list(filter(lambda x :(x%2==0),mylist)))
print(f"{type(total)}")
print('total=',total)
mylist=[n for n in range(0,10)]
mylist.reverse()
print(mylist)
#8 - 6 - 4 - 2 == -4
total = reduce(lambda x,y:x-y,list(filter(lambda x :(x%2==0),mylist)))
print(f"{type(total)}")
print('total=',total)
字符串转数字
这是在
from functools import reduce
def charToInt(s):
print('s = ',type(s),s)
mychars=''.join([chr(n) for n in range(ord('0'),ord('9') + 1)])
mynumbers=[n for n in range(0,10)]
mydict=dict(zip(mychars,mynumbers))
n = mydict[s]
print("n = ",n)
return n
x = list(map(charToInt,'4567'))
print('x = ',type(x),x)
from functools import reduce
def strToInt(s):
def fun(x,y):
return x*10+y
def charToInt(s):
print('s = ',type(s),s)
mychars=''.join([chr(n) for n in range(ord('0'),ord('9') + 1)])
mynumbers=[n for n in range(0,10)]
mydict=dict(zip(mychars,mynumbers))
n = mydict[s]
print("n = ",n)
return n
return reduce(fun,map(charToInt,s))
string='4567'
x = strToInt(string)
print(x)
简化上面的代码就是
from functools import reduce
total = reduce(lambda x,y:x*10+y,map(lambda c:dict(zip('0123456789',range(0,10)))[c] ,'4567'))
print('x = ',type(total),total)