查看: 1631|回复: 0

Python笔记|Python3中没有reduce函数的原因

[复制链接]

665

主题

1234

帖子

6576

积分

xdtech

Rank: 5Rank: 5

积分
6576
发表于 2019-3-13 23:01:38 | 显示全部楼层 |阅读模式
Guido大大原计划把 lambda, reduce 都干掉。

最后只干掉了 reduce

使用

首先在python3版本中,直接使用reduce()的话,系统会报错,提示不存在reduce()函数。

>>> arr = [1, 2, 3, 4, 5]
>>> reduce(lambda x, y : x+y, arr)
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    reduce(lambda x, j : x+y, arr)
NameError: name 'reduce' is not defined
1
2
3
4
5
6
在Python 3里,reduce() 函数已经被从全局名字空间里移除了,它现在被放置在fucntools 模块里

使用前需要先引用

>>> from functools import reduce
>>> arr = [1, 2, 3, 4, 5]
>>> reduce(lambda x, y : x+y, arr)
15
---------------------


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表