224

我正在使用 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 中被删除了吗?如果是这种情况,有什么替代方案?

4

5 回答 5

325

它被移到functools.

于 2011-12-31T16:27:38.573 回答
249

你可以加

from functools import reduce

在你使用reduce之前。

于 2015-04-01T08:59:51.920 回答
10

或者如果你使用六库

from six.moves import reduce
于 2015-11-10T20:15:51.143 回答
2

在这种情况下,我相信以下是等价的:

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

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

于 2015-03-26T01:35:50.450 回答
1

你需要从functoolspython 包安装和导入reduce

于 2020-09-18T08:50:46.703 回答