标签:cto pre color 默认 迭代 bsp 接收 tor 序列
reduce()函数接收两个参数:函数和可迭代对象,计算过程如下:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
求和1到100:
>>> from functools import reduce >>> def add(x,y): return x+y >>> reduce(add,list(range(101))) 5050
用自带sum( )函数实现:
>>> sum(list(range(101)),) a、sum()接收两个参数:可迭代对象和初始值,初始值不写默认为0. b、range(101)得到从0到100
5050
将整数序列[1,3,5,7,9]变成整数13579:
>>> from functools import reduce >>> def fn(x,y): return x*10+y >>> reduce(fn,[1,3,5,7,9]) 13579
str2int:(用map把str变成序列再用reduce变序列为整数)
>>> from functools import reduce >>> def fn(x,y): return x*10+y >>> def char2num(s): return{‘0‘: 0, ‘1‘: 1, ‘2‘: 2, ‘3‘: 3, ‘4‘: 4, ‘5‘: 5, ‘6‘: 6, ‘7‘: 7, ‘8‘: 8, ‘9‘: 9}[s] (字典通过key取value s为对应的key) >>> reduce(fn,map(char2num,‘13579‘)) 将map得到的iterator直接作为reduce的iterable 13579
reduce接收list求所有元素积
>>> from functools import reduce >>> def prod(x,y): return x*y >>> reduce(prod,[3,5,7,9]) 945
标签:cto pre color 默认 迭代 bsp 接收 tor 序列
原文地址:http://www.cnblogs.com/sniperlr/p/7286578.html