NameError:未定义全局名称“reduce" [英] NameError: global name 'reduce' is not defined

查看:64
本文介绍了NameError:未定义全局名称“reduce"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手.你能告诉我下面的代码有什么问题吗?当我运行它时,我收到一条错误消息NameError: global name 'reduce' is not defined".我问过谷歌,但没用.:(

I'm new to Python. Would you please tell me what's wrong with the following code? When I run it, I got an error message of "NameError: global name 'reduce' is not defined". I asked Goolge but it's useless. :(

def main():
    def add(x,y): return x+y
    reduce(add, range(1, 11))

if __name__=='__main__':
    main()

推荐答案

我猜:

  1. 您使用的是 Python 3,并且
  2. 您正在学习专为 Python 2 设计的教程.

reduce 函数,由于它不常用,从 Python 3 的内置函数中删除.它在 functools 模块中仍然可用,所以你可以这样做:

The reduce function, since it is not commonly used, was removed from the built-in functions in Python 3. It is still available in the functools module, so you can do:

import functools

def main():
    def add(x,y): return x+y
    functools.reduce(add, range(1, 11))

这篇关于NameError:未定义全局名称“reduce"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆