问题:NameError:名称“ reduce”未在Python中定义

我正在使用Python 3.2。试过这个:

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

并得到以下错误:

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

尝试打印reduce到交互式控制台中-出现此错误:

NameError: name 'reduce' is not defined


reduce在Python 3.2中真正删除的吗?如果是这样,还有什么选择?

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?


回答 0

它已移至functools


回答 1

你可以加

from functools import reduce

在使用reduce之前。

You can add

from functools import reduce

before you use the reduce.


回答 2

或者如果您使用六个库

from six.moves import reduce

Or if you use the six library

from six.moves import reduce

回答 3

在这种情况下,我认为以下内容是等效的:

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

唯一的问题是它会产生大量数字,但这也许比重复的模运算更好?

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?


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。