NameError: name 'reduce' is not defined

听说了大名鼎鼎的 reduce 函数,可以是执行的时候却显示这个。

In [1]: reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-4c41a726eae1> in <module>()
----> 1 reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])

NameError: name 'reduce' is not defined

原来自 Python3 之后,这个函数从全局命名空间中移除,放在了 functools模块,因为如果想正确执行,必须这样

In [2]: from functools import reduce

In [3]: reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
Out[3]: 15

参考资料:
1、functools

原文地址:https://www.cnblogs.com/cocowool/p/8459492.html