NameError: global name 'reduce' is not defined

前端 未结 2 1236
北荒
北荒 2020-12-17 08:27

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 defin

相关标签:
2条回答
  • 2020-12-17 08:53

    Also

    # Import reduce from functools
    from functools import reduce
    

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

    def main():
        def add(x,y): return x+y
        reduce(add, range(1, 11))
    
    0 讨论(0)
  • 2020-12-17 09:00

    I'm going to guess that:

    1. You are using Python 3, and
    2. You are following a tutorial designed for 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:

    import functools
    
    def main():
        def add(x,y): return x+y
        functools.reduce(add, range(1, 11))
    
    0 讨论(0)
提交回复
热议问题