NameError: name 'reduce' is not defined in Python

痞子三分冷 提交于 2019-11-26 11:56:16

问题


I\'m using Python 3.2. Tried this:

xor = lambda x,y: (x+y)%2
l = reduce(xor, [1,2,3,4])

And got the following error:

l = reduce(xor, [1,2,3,4])
NameError: name \'reduce\' is not defined

Tried printing reduce into interactive console - got this error:

NameError: name \'reduce\' is not defined


Is reduce really removed in Python 3.2? If that\'s the case, what\'s the alternative?


回答1:


It was moved to functools.




回答2:


You can add

from functools import reduce

before you use the reduce.




回答3:


Or if you use the six library

from six.moves import reduce



回答4:


In this case I believe that the following is equivalent:

l = sum([1,2,3,4]) % 2

The only problem with this is that it creates big numbers, but maybe that is better than repeated modulo operations?



来源:https://stackoverflow.com/questions/8689184/nameerror-name-reduce-is-not-defined-in-python

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