聽說了大名鼎鼎的 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
