您的位置:首页 > 编程语言 > Python开发

python3.x中lambda表达式遇到的一些问题以及解决办法

2015-11-03 11:55 639 查看
lambda表达式

在python3中 使用reduce,map会和2.x版本有很多区别

想正常展示结果,需要一些一些动作。

map函数,不再返回 数组,需要转换

例如

map(lambda x: x ** 2, [1, 2, 3, 4, 5])

将会显示成:

<map object at 0x0000000002D4F898>

需要转换一下

>>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))

[1, 4, 9, 16, 25]

>>> list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))

[3, 7, 11, 15, 19]

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, 6], 1)

21

>>> reduce(lambda x, y: x + y, [2, 3, 4, 5, 6])

20
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: