python3.x中lambda表达式的处理与python2不一样

lambda表达式,在python2中的表达式和python3不同,原来只要:

>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])                    原来python2
[1, 4, 9, 16, 25]

>>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))             现在python3
[1, 4, 9, 16, 25]

在python3中使用reduce函数:在Python 3里,reduce()函数已经被从全局名字空间里移除了,它现在被放置在fucntools模块里用的话要先导入:

>>> from functools import reduce

reduce函数的定义:
reduce(function, sequence[, initial]) -> value
function参数是一个有两个参数的函数,reduce依次从sequence中取一个元素,和上一次调用function的结果做参数再次调用function。
第一次调用function时,如果提供initial参数,会以sequence中的第一个元素和initial作为参数调用function,否则会以序列sequence中的前两个元素做参数调用function。 

>>> reduce(lambda x,y: x + y, [2, 3, 4, 5], 1)
15
>>> reduce(lambda x,y: 2*x + 3*y, [2, 3, 4, 5], 1)
139

原文地址:https://www.cnblogs.com/guochaoxxl/p/11919526.html