您的位置:首页 > 编程语言 > Python开发

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

2017-12-27 11:12 936 查看

问题来了

使用 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: