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(lambda x, y: x + y, [2, 3, 4, 5, 6], 1)
21
>>> reduce(lambda x, y: x + y, [2, 3, 4, 5, 6])
20
本文深入探讨了Python 3中map和reduce函数的使用方式,包括它们与Python 2.x版本的区别、如何正确使用map函数将结果转换为列表,以及在Python 3中引入reduce函数的方法和应用实例。
835

被折叠的 条评论
为什么被折叠?



