NameError:未定义全局名称'reduce'

时间:2021-08-29 20:27:13

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. :(

我是Python的新手。你能告诉我下面这段代码有什么问题吗?当我运行它时,我收到一条错误消息“NameError:全局名称'reduce'未定义”。我问Goolge但它没用。 :(

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

if __name__=='__main__':
    main()

2 个解决方案

#1


50  

I'm going to guess that:

我猜这个:

  1. You are using Python 3, and
  2. 您正在使用Python 3和

  3. You are following a tutorial designed for Python 2.
  4. 您正在关注为Python 2设计的教程。

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:

reduce函数,因为它不常用,已从Python 3中的内置函数中删除。它仍可在functools模块中使用,因此您可以执行以下操作:

import functools

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

#2


4  

Also

# Import reduce from functools
from functools import reduce

Allows you to use reduce as though it were a built in function.

允许您使用reduce,就像它是内置函数一样。

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

#1


50  

I'm going to guess that:

我猜这个:

  1. You are using Python 3, and
  2. 您正在使用Python 3和

  3. You are following a tutorial designed for Python 2.
  4. 您正在关注为Python 2设计的教程。

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:

reduce函数,因为它不常用,已从Python 3中的内置函数中删除。它仍可在functools模块中使用,因此您可以执行以下操作:

import functools

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

#2


4  

Also

# Import reduce from functools
from functools import reduce

Allows you to use reduce as though it were a built in function.

允许您使用reduce,就像它是内置函数一样。

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