**reduce函数** reduce 在Python3.5 中的源码,只摘录了下面咱们比较关注的部分 ~~~ def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__ """ reduce(function, sequence[, initial]) -> value 从左向右对序列中的每两个元素应用函数,直到序列最后的一个值。 Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. """ pass ~~~ reduce 在 Python 内置的 _functools 模块中 reduce 是没有办法直接使用的,在没引入 functools 模块时使用 reduce 方法,会报 reduce 未定义的错误 ~~~ >>> def add(x,y):return x+y ... >>> reduce(add,[1,2,3,4]) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'reduce' is not defined ~~~ 那如何使用呢?模块的使用我们之后的章节会讲,现在先知道可以向下面这么使用就可以 ~~~ >>> from functools import reduce >>> def add(x,y):return x+y ... >>> reduce(add,[1,2,3,4]) 10 ~~~ reduce(add,[1,2,3,4]) 等价于 (((1+2)+3)+4) 所以最终结果是 10 。 **Demo** 在 map 那一讲,我们已经把 数字字符串 转换成 整形 列表 现在更进一步,将 数字字符串 转换成 整形 ~~~ >>> from functools import reduce #引入模块 >>> >>> 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] #数字字符串 转换成 整形 列表 ... >>> reduce(lambda x,y:x*10+y,list(map(char2num,'12345'))) #数字字符串 转换成 整形 12345 >>> type(reduce(lambda x,y:x*10+y,list(map(char2num,'12345')))) #查看类型 <class 'int'> ~~~ 总结:reduce 传递的函数的参数必须有两个。