天天看點

Python程式設計:NameError: name 'reduce' is not defined

問題來了

使用 reduce() 測試的時候報錯:reduce 未定義!

print(reduce(lambda x, y: x + y, [ 1, 2, 3]))

"""Output:
NameError: name 'reduce' is not defined
"""      

解決

引用stackoverflow的回答:

- 你使用的是python3

- 參考的是python2的指南

from functools import reduce  # py3

print(reduce(lambda x, y: x + y, [ 1, 2, 3]))

"""Output:
6
"""      

reduce函數在python3的内建函數移除了,放入了functools子產品

參考: NameError: global name ‘reduce’ is not defined

連接配接:

https://stackoverflow.com/questions/10226381/nameerror-global-name-reduce-is-not-defined