zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python编程:NameError: name 'reduce' is not defined

Python编程 not is name defined reduce
2023-09-14 09:07:12 时间

问题来了

使用 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