NameError: global name 'reduce' is not defined

允我心安 提交于 2019-11-29 05:27:07

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))

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))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!